📜 ⬆️ ⬇️

Yii2. Acquaintance

Introduction

The other day, an event happened, which I think many more people have been waiting for. The authors of the Yii Framework rolled out a preview version.

A day later, a tutorial material appeared on the Habré, the reading of which caused strange impressions and after the weekend spent on studying the Yii2 code, I decided to write my version. Hopefully not worse.

Start

The second version differs from the first cardinally. List in short form:
')
- Separated the core from the add-ons. Thrown out a lot of classes. Some of them will be moved to separate, officially supported extensions. Part simply removed as unnecessary.

- Base CComponent divided into Object and Component . The first carries out the work of the getters and setters, the second extends the first, adding events and behaviors.

- Changed the connection of events and behaviors. Subscribing to the event
$post->on('update', function($event) { // send email notification }); 

Customize the component
 $component = \Yii::createObject(array( 'class' => '\app\components\GoogleMap', 'apiKey' => 'xyz', //   'on eventName' => array('Event', 'run'), //   'as behaviorName' => array(/* Behavior config */), )); 

- Added a new class View , now we have a real MVC framework. Representation
 <?php use yii\helpers\base\Html; /** *   $this      . *     $this->context * @var yii\base\View $this */ $this->title = 'Hello world'; ?> <h1><?php echo Html::encode($this->title); ?></h1> <p class="lead"> !</p> 
* View can be installed for each controller, or use the base for the application.

- render () controller displays nothing more. It returns data
 public function actionIndex() { echo $this->render('index'); } 

- There are two events in the controller that you can subscribe to: beforeAction , afterAction
 public function init() { $this->on('beforeAction', function($event) { //   $event->isValid = false; }); } 

- Removed CFilter controller filters , now everything is done through behaviors
 public function behaviors() { return array( 'AccessControl' => array( 'class' => '\yii\web\AccessControl', 'rules' =>array(/*     */), ), ); } 

- A great helper appeared in the controller - the populate method
 public function actionLogin() { $model = new LoginForm(); if ($this->populate($_POST, $model) && $model->login()) { Yii::$app->response->redirect(array('site/index')); } echo $this->render('login', array( 'model' => $model, )); } 

- Added a few more static helper classes: ArrayHelper , StringHelper , SecurityHelper . All helpers can now be blocked via LSB. Hooray, I exclaimed, because I personally more than once needed to block Html .

- The ActiveForm widget is also rewritten, and most likely will replace the CForm form- builder . Each form field can now be represented as an ActiveField object that creates an ActiveForm.
 $form = $this->beginWidget('yii\widgets\ActiveForm', array( 'options' => array('class' => 'form-horizontal') )); echo $form->field($model, 'username')->textInput(); echo $form->field($model, 'password')->passwordInput(); echo $form->field($model, 'rememberMe')->checkbox(); echo Html::tag('div', Html::submitButton('Login', null, null, array('class' => 'btn btn-primary')), array( 'class' => 'form-actions' )); $this->endWidget(); 
* Attention: in Html :: tag ($ tag, $ content, $ options) - changed the order of the parameters!

ActiveRecord

"For the most part, ActiveRecord has remained untouched."
- written in the previous article. Rightly noticed - do not touch.
Just took and wrote a completely different ActiveRecord.

- Forget about model ()

- Removed CDbCriteria . But do not worry, work with the base has become easier. Appeared ActiveQuery , which is a hybrid CActiveFinder and CDbCriteria .
 //   ActiveQuery $query = Post::find(); //   $posts = $query->all(); //      $posts = $query ->where(array('status' => Post::DRAFT)) ->orderBy('time') ->all(); //    $post = $query ->where(array('id' => 10, 'status' => Post::READ)) ->one(); //  ,  where       $post = Post::find(array('id' => 10, 'status' => Post::READ)); //              $post = Post::find(10) ->where(array('status' => Post::READ)) ->one(); //      $posts = $query->indexBy('title')->all(); //     $posts = $query->asArray()->all(); 

- All common methods are now static: getDb , tableName , find *, saveAll *, primaryKey . The win is obvious.

- Connections, where without them. Links are now determined by the addition of getters.
 class Post extends ActiveRecord { public function getCreator() { return $this->hasOne('User', array('id' => 'user_id')); } public function getComments() { return $this->hasMany('Comment', array('post_id' => 'id')); } public function getTrustComments($isTrust = true) { return $this->hasMany('Comment', array('post_id' => 'id')) ->where('status = :status', array( ':status' => $isTrust ? self::TRUST : self::UNTRUST, )) ->orderBy('id'); } } 

- For the convenience of working with links added link () and unlink (), which will automatically arrange the keys
 $post = Post::find(1); $comment = new Comment(); $comment->text = 'Yii Framework is cool!'; $post->link('comments', $comment); 

- Named condition groups exist, but in a different form. We have no more CDbCriteria , and therefore there are no more condition arrays either. Now it is methods, and static, adding conditions in Query
 class Post extends \yii\db\ActiveRecord { /** * @param ActiveQuery $query */ public static function byCreator($query, $userId) { $query->andWhere('user_id = :userId', array('userId' => $userId)); } /** * @param ActiveQuery $query */ public static function removed($query) { $query->andWhere('removed = 1'); } } $posts = Post::find()->removed()->all(); $myPosts = Post::find()->byCreator(Yii::$app->user->id)->all(); 


Everything

At this point. The article turned out a lot, a lot of code, but I hope you survived and read it.

Before communication.

Source: https://habr.com/ru/post/178917/


All Articles