The core of YII2 is dependency injection and event handling, which is essentially the same as spring's IOC and AOP functions, and Yii's dependency injection allows us to use objects when Yii's containers help us create significantly more efficient, and part of the increased memory utilization, If we control the object, the process may waste unnecessary content space, yii events, like AOP,AOP I do Java development is the most time to log control, and the control of things, as well as permissions. This can also be achieved with YII events.
eg
IOC also known as DI (Dependency injection)
First: I created the service folder below the Frontend folder to hold the implementation classes for the custom interfaces and interfaces that were created.
iuserservice.php
<?phpnamespace frontend\service;/** * User Business logic interface * /interface iuserservice{public function getAllUsers (); Public Function Getuserbyid ($id);
Iuserserviceimpl.php interface Implementation Class
<?php namespace Frontend\service;use frontend\models\user;use yii\base\object;/** * User business logic Implementation * Implement User business Logic interface * */ class Iuserserviceimpl extends Object implements iuserservice{public function __construct () { parent::__ Construct (); } Public Function GetAllUsers () { //$list = User::find ()->asarray ()->all (); $user = new User (); $list = User::getinstance ()->getallusers (); Return $list? $list: []; } Public Function Getuserbyid ($id) { return user::findone ($id); } }
Model Layer user.php
<?php namespace Frontend\models;use yii\base\model;use yii\db\activerecord;use yii;use frontend\models\Order;use Yii\web\identifyinterface; Class User extends ActiveRecord {///First step: Define your own event const Event_before_mark_query = ' Beforemarkdelete '; Const Event_after_mark_query = ' Aftermarkdelete '; First step: Bind events and Event Handler Public function init () {parent::init () during initialization phase; $this->trigger (Self::event_init); Complete the binding $this->on (Self::event_before_mark_query, [$this, ' onbeforemarkquery ']); $this->on (self::event_after_mark_query,[$this, ' onaftermarkquery '); }//Second step: Define the event Handler Public Function Onbeforemarkquery () {echo "I intercepted before querying.") <br> "; Exit }//Second step: Define event Handler Public Function Onaftermarkquery () {echo "query finished, want to return data, don't think, data On the top, go get it "; Exit } /** * Get all user information */Public function getAllUsers () {//trigger event $this->t Rigger (Self::event_before_mark_query); $list = Static::find ()->asarray ()->all (); echo "<pre>"; Print_r ($list); $this->trigger (self::event_after_mark_query); /** * Instantiate the User object * @return User */public static function getinstance () { return new self; }/** * Returns the table name */public static function TabName () {return ' user '; /** * Returns the current database connection information */public static function Getdbinfo () {return Parent::getdb ( ); } }Next, configure the implementation of the interface:
Config inside the portal file index.php
<?phpdefined (' yii_debug ') or define (' Yii_debug ', true);d efined (' yii_env ') or define (' yii_env ', ' dev '); require (__ dir__. '/.. /.. /vendor/autoload.php '); require (__dir__. '/.. /.. /vendor/yiisoft/yii2/yii.php '); require (__dir__. '/.. /.. /common/config/bootstrap.php '); require (__dir__. '/.. /config/bootstrap.php '); $config = Yii\helpers\arrayhelper::merge ( require (__dir__. '/.. /.. /common/config/main.php '), require (__dir__. '/.. /.. /common/config/main-local.php '), require (__dir__. '/.. /config/main.php '), require (__dir__. '/.. /config/main-local.php ');//Register an interface Yii:: $container->set (' Frontend\\service\\iuserservice ', ' Frontend\\service \\IUserServiceimpl ');//Register an alias Yii:: $container->set (' UserService ', ' frontend\\service\\iuserservice ');// Define the path alias Yii::setalias (' @getuser ', ' index.php?r=face/getusers ');//load configuration file $application = new Yii\web\application ($ config); $application->run ();
Create a controller to test:
<?php namespace Frontend\controllers;use yii;use frontend\service\iuserservice;use yii\web\controller;use yii\di\ Container;use Yii\helpers\arrayhelper;use Frontend\models\userform; Class Facecontroller extends controller{private $userService; public function __construct ($id, $module, $config = []) {// The Di container gets the instantiated object//$this->userservice = \yii:: $container->get (' UserService '); Service Locator obtains the instance through Yii::createobject (), and this yii::createobject ()//is called the Yii\di\container::get () of the Di container to yii::$ Container to ask for an example. Therefore, the Service locator is ultimately created and fetched from the Di container. $this->userservice = \yii::createobject (' UserService '); Parent::__construct ($id, $module, $config); }/** * @inheritdoc */Public Function actions () {return [' error '] = [ ' Class ' = ' yii\web\erroraction ',], ' captcha ' = [' class ' and ' = ' yii\capt Cha\captchaaction ', ' fixedverifycode ' = yii_env_test? ' Testme ': null, ], ]; }/** * Get all users * */Public Function actiongetusers () {$list = $this->userservice->getallusers () ; echo "<pre>"; Print_r ($list); Exit Public Function Actiongetuserbyid () {$user = $this->userservice->getuserbyid (' 2 '); $user = Arrayhelper::toarray ($user); echo "<pre>"; Print_r ($user); Exit } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
YII2 Dependency Injection and event usage