📜 ⬆️ ⬇️

Website creation on Yii 2 (blog, basic) - Part 1

image

Hello! I will try to describe in detail the process of developing a basic version of a blog using Yii 2 (basic) for educational purposes.

Why basic? If you take up advanced, you can easily get confused at the first couple.

Before starting, I will talk about software:
')

Recommendations:


1) Configure the database and create tables


So, you somehow installed Yii 2 basic, you checked the work of the standard script.
I propose to start with setting up the database, I will use MySQL and phpMyAdmin.

Yii needs information about the database, go to one of the application configuration files, namely in basic \ config \ db.php :

return [ 'class' => 'yii\db\Connection', //    'dsn' => 'mysql:host=localhost;dbname=yii2basic', //   , URL 'username' => 'root', //     'password' => '', //     'charset' => 'utf8', //  ]; 

Standard parameters are the same as those I need. This data will be used by the yii \ db \ Connection class (also specified in the parameters) to initialize and create an instance of this class, and accordingly the classes with access to the DB.

In this case, we need several tables:


I will add new tables to the database through migrations , they will help to communicate between individual databases. It is not necessary to apply migrations, but this will allow you to apply / cancel / apply_read / watch_migration_ history in each individual copy of the application.

So, to create a migration, you need to chat with the yii.bat file located in the basic directory of the application.

I will communicate through the command line windows
Directory change:
 cd C:\xampp\htdocs\Yii2St\basic 


Creating migrations for user and post tables (table for articles):

Code after cd:

 yii migrate/create create_post_table 

(For table post)

 yii migrate/create create_user_table 

(For user table)

Yii will create a migrations folder if it is not there. Now there are 2 files and classes for the two above created migrations.

Head over to
basic \ migrations \ m170304_160410_create_user_table .
We make changes to the “up” function, do the same table as in the advanced version:

  public function up() //   { $tableOptions = null; if ($this->db->driverName === 'mysql') { //  ,         . $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('user', [ 'id' => $this->primaryKey(), 'username' => $this->string()->notNull()->unique(), 'auth_key' => $this->string(32)->notNull(), 'password_hash' => $this->string()->notNull(), 'password_reset_token' => $this->string()->unique(), 'email' => $this->string()->notNull()->unique(), 'status' => $this->smallInteger()->notNull()->defaultValue(10), 'created_at' => $this->integer()->notNull(), 'updated_at' => $this->integer()->notNull(), ], $tableOptions); } 


We also make changes for articles in the basic \ migrations \ m170304_160323_create_post_table :

  public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('post', [ 'id' => $this->primaryKey(), 'author_id' => $this->integer()->notNull(), // 'date' => $this->integer()->notNull(), 'category_id' => $this->integer()->notNull(), //  'text' => $this->text()->notNull(), 'title' => $this->string()->notNull()->unique(), //   'abridgment' => $this->text()->notNull(), //   'activity' => $this->integer()->notNull()->defaultValue(0), //   ], $tableOptions); } 

Then simply execute this code in the console:

 yii migrate 

If it is simpler to say, this command executes the up methods in the migration classes + updates / adds the table 'migration', accordingly the down method reverses the changes.

Tables are ready.

image

2) Adding the function of registration / login through DB



(About the User component and IdentityInterface )

In Yii, there is a component of the User application, it controls the status of user authentication, for example:

 Yii::$app->user->isGuest; //  false,    Yii::$app->user->logout(); //    Yii::$app->user->identity->username //  username  //  .. 

It requires you to specify an identity class that will contain the current authentication logic:

 $config = [ ... 'components' => [ .... 'user' => [ 'identityClass' => 'app\models\User', //      User ], .... ] ... ]; 


In the standard User model, the storage of logins and passwords (etc.) looks like this (code from User itself):
  private static $users = [ '100' => [ 'id' => '100', 'username' => 'admin', 'password' => 'admin', 'authKey' => 'test100key', 'accessToken' => '100-token', ], '101' => [ 'id' => '101', 'username' => 'demo', 'password' => 'demo', 'authKey' => 'test101key', 'accessToken' => '101-token', ], ]; 

Naturally registration with the standard model will be difficult to implement, all we need for a complete, convenient connection with the database is ActiveRecord, it will determine the properties in the class based on the rows in the table of the same name with the class name.
For example:
 $model->id; //  id  $model->id = 5; //  id $model->save(); //      

Also, do not forget that the User component requires that the class it needs to implement the IdentityInterface interface for its personal purposes.
basic \ models \ User :

 namespace app\models; use Yii; use yii\base\NotSupportedException; use yii\db\ActiveRecord; use yii\web\IdentityInterface; class User extends ActiveRecord implements IdentityInterface { //       ID    ,   'status'   SCATUS_ACTIVE const STATUS_DELETED = 0; //   () const STATUS_ACTIVE = 10; //    const STATUS_ADMIN = 1; //   (  II) //     public static function findIdentity($id) { return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]); } public static function findIdentityByAccessToken($token, $type = null) { throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.'); } public static function findByUsername($username) { return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]); } public function getId() { return $this->getPrimaryKey(); } public function getAuthKey() { return $this->auth_key; } public function validateAuthKey($authKey) { return $this->getAuthKey() === $authKey; } public function validatePassword($password) { return Yii::$app->security->validatePassword($password, $this->password_hash); } public function setPassword($password) { $this->password_hash = Yii::$app->security->generatePasswordHash($password); } public function generateAuthKey() { $this->auth_key = Yii::$app->security->generateRandomString(); } } 

To implement the registration, we will add a separate model, although almost the same registration method can be implemented in the User model, it is better not to clog the constantly used model + the new model will be used by the registration type.

basic \ models \ SignupForm.php :
(About validate () and rules )

 namespace app\models; use Yii; use yii\base\Model; class SignupForm extends Model { public $username; public $email; public $password; public function rules() //      :  ,     validate(),       { return [ ['username', 'trim'], //      null     ['username', 'required'], // 'username'    ['username', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This username has already been taken.'], // 'username'   \app\models\User(    user( ActivityRecords)   ) ['username', 'string', 'min' => 2, 'max' => 255], // 'username'  string     2  255  ['email', 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'string', 'max' => 255], ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This email address has already been taken.'], ['password', 'required'], ['password', 'string', 'min' => 6], ]; } public function attributeLabels() //    { return [ 'username' => '', 'email' => ' ', 'password' => '', ]; } public function signup() //  { if (!$this->validate()) { //    false   null return null; } $user = new User(); //  AcriveRecord User $user->username = $this->username; //    $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); $user->created_at = time(); return $user->save() ? $user : null; //    ( ActivityRecord) user     null } } 

Add a registration action to the standard controller
basic \ controllers \ SiteController.php :

  //.... public function actionSignup() { $model = new SignupForm(); //      : use app\models\SignupForm;   'new SignupForm()'  '\app\models\SignupForm()' if ($model->load(Yii::$app->request->post())) { //  ,  post       load  Model if ($user = $model->signup()) { //  if (Yii::$app->getUser()->login($user)) { //      return $this->goHome(); //     } } } return $this->render('signup', [ //       if  false 'model' => $model, ]); } //.... 

Next you need to add a signup view for form input.
basic \ views \ site \ signup.php :

 use yii\helpers\Html; use yii\bootstrap\ActiveForm; $this->title = ''; $this->params['breadcrumbs'][] = $this->title; // <--   ?> <div class="site-signup"> <h1><?= Html::encode($this->title) ?></h1> <div class="row"> <div class="col-lg-5"> <?php $form = ActiveForm::begin(['id' => 'form-signup']); ?> <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?> <?= $form->field($model, 'email') ?> <?= $form->field($model, 'password')->passwordInput() ?> <div class="form-group"> <?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div> 

Change Navbar
basic \ views \ layouts

 //    NavBar::begin(),  NavBar::end() NavBar::begin([ 'brandLabel' => 'My Company', //   'brandUrl' => Yii::$app->homeUrl, // Url        'options' => [ 'class' => 'navbar-inverse navbar-fixed-top', //  bootstrap class="navbar-inverse navbar-fixed-top"  HTML ], ]); $menuItems = [ // ,     ['label' => '', 'url' => ['/site/index']], ['label' => '', 'url' => ['/site/contact']], ]; if(Yii::$app->user->isGuest) //     { $menuItems[] = ['label' => '', 'url' => ['/site/signup']]; $menuItems[] = ['label' => '', 'url' => ['/site/login']]; } else { $menuItems[] = ['label' => '', 'url' => ['/post']]; $menuItems[] = '<li>' . Html::beginForm(['/site/logout'], 'post') //  ,   ActiveForm . Html::submitButton( ' (' . Yii::$app->user->identity->username . ')', ['class' => 'btn btn-link logout'] ) . Html::endForm() . '</li>'; } echo Nav::widget([ //    'options' => ['class' => 'navbar-nav navbar-right'], 'items' => $menuItems //   ]); NavBar::end(); 

For localization, you need to specify the following code in the configuration:
basic \ config \ web.php :

 return [ 'id' => 'basic', 'basePath' => dirname(__DIR__), // ... 'language' => 'ru-RU', // <-  ! // ... ] 

About localization

3) Add CRUD for articles


CRUD allows you to add, edit, view and delete an article. The quickest way to add a CRUD in our case is gii . Gii automatically generates the code, after which you just need to change the generated code.

Go to the url with get ? R = gii
For CRUD, a model is needed, I generate a new one:

(The description can be viewed by simply hovering the cursor over the form label)

image

Next, fill in the forms and generate the CRUD itself:

image

Check CRUD possible through this get ? R = post

PS End of the first part.
PPS First article, judge strictly.

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


All Articles