Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Yii2 Application Development Cookbook

You're reading from   Yii2 Application Development Cookbook Discover 100 useful recipes that will bring the best out of the Yii2 framework and be on the bleeding edge of web development today

Arrow left icon
Product type Paperback
Published in Nov 2016
Publisher
ISBN-13 9781785281761
Length 584 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Dmitry Eliseev Dmitry Eliseev
Author Profile Icon Dmitry Eliseev
Dmitry Eliseev
Andrew Bogdanov Andrew Bogdanov
Author Profile Icon Andrew Bogdanov
Andrew Bogdanov
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Fundamentals FREE CHAPTER 2. Routing, Controllers, and Views 3. ActiveRecord, Model, and Database 4. Forms 5. Security 6. RESTful Web Services 7. Official Extensions 8. Extending Yii 9. Performance Tuning 10. Deployment 11. Testing 12. Debugging, Logging, and Error Handling Index

Working with events

Yii's events provide a simple implementation, which allows you to listen and subscribe to various events that occur in your web-application. For example, you may wish to send a notification about a new article to followers each time you publish new material.

Getting ready

  1. Create a new application by using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
  2. Execute the following SQL code on your server to create the article table:
    CREATE TABLE `article` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) DEFAULT NULL,
    `description` TEXT,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  3. Generate the Article model using Gii.
  4. Run your webserver by ./yii serve command.

How to do it…

  1. Add an action test to \controllers\SiteController:
    public function actionTest()
    {
        $article = new Article();
        $article->name = 'Valentine\'s Day\'s coming? Aw crap! I forgot to get a girlfriend again!';
        $article->description = 'Bender is angry at Fry for dating a robot. Stay away from our women.
        You\'ve got metal fever, boy. Metal fever';
    
        // $event is an object of yii\base\Event or a child class
        $article->on(ActiveRecord::EVENT_AFTER_INSERT, function($event) {
            $followers = ['john2@teleworm.us', 'shivawhite@cuvox.de', 'kate@dayrep.com' ];
            foreach($followers as $follower) {
                Yii::$app->mailer->compose()
                    ->setFrom('techblog@teleworm.us')
                    ->setTo($follower)
                    ->setSubject($event->sender->name)
                    ->setTextBody($event->sender->description)
                    ->send();
            }
            echo 'Emails has been sent';
        });
    
        if (!$article->save()) {
            echo VarDumper::dumpAsString($article->getErrors());
        };
    }
  2. Update the config/web.php component mailer using the following code.
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'useFileTransport' => false,
    ],
  3. Run this URL in your browser: http://localhost:8080/index.php?r=site/test.
  4. Also check http://www.fakemailgenerator.com/inbox/teleworm.us/john2/.
    How to do it…

How it works…

We've created an Article model and added a handler for the ActiveRecord::EVENT_AFTER_INSERT event to our Article model. It means that every time we save a new article an event is triggered and our attached handler will be called.

In the real-world, we would like to notify our blog followers each time we publish a new article. In a real application we would have a follower or user table and with different blog sections not only single blog. In this example, after saving our model we notify our followers john2@teleworm.us, shivawhite@cuvox.de, and kate@dayrep.com. In the last step we just prove that users have received our notifications, particularly john2. You can create your own event with any name. In this example we use a built-in event called ActiveRecord::EVENT_AFTER_INSERT, which is called after each insert to the database.

For example, we can create our own event. Just add a new actionTestNew with the following code:

public function actionTestNew()
{
    $article = new Article();
    $article->name = 'Valentine\'s Day\'s coming? Aw crap! I forgot to get a girlfriend again!';
    $article->description = 'Bender is angry at Fry for dating a robot. Stay away from our women.
    You've got metal fever, boy. Metal fever';

    // $event is an object of yii\base\Event or a child class
    $article->on(Article::EVENT_OUR_CUSTOM_EVENT, function($event) {
        $followers = ['john2@teleworm.us', 'shivawhite@cuvox.de', 'kate@dayrep.com' ];
        foreach($followers as $follower) {
            Yii::$app->mailer->compose()
                ->setFrom('techblog@teleworm.us')
                ->setTo($follower)
                ->setSubject($event->sender->name)
                ->setTextBody($event->sender->description)
                ->send();
        }
        echo 'Emails have been sent';
    });

    if ($article->save()) {
        $article->trigger(Article::EVENT_OUR_CUSTOM_EVENT);
    }
}

Also add the EVENT_OUR_CUSTOM_EVENT constant to models/Article as:

class Article extends \yii\db\ActiveRecord
{
    CONST EVENT_OUR_CUSTOM_EVENT = 'eventOurCustomEvent';
…
}

Run http://localhost:8080/index.php?r=site/test-new.

You should see the same result and all notifications to followers will be sent again. The main difference is we used our custom event name.

After the save, we've triggered our event. Events may be triggered by calling the yii\base\Component::trigger() method. The method requires an event name, and optionally an event object that describes the parameters to be passed to the event handlers.

See also

For more information about events refer to http://www.yiiframework.com/doc-2.0/guide-concept-events.html

You have been reading a chapter from
Yii2 Application Development Cookbook - Third Edition
Published in: Nov 2016
Publisher:
ISBN-13: 9781785281761
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image