Yii Behaviors - Yii

What are Yii Behaviors?

The instances of the yiibaseBehavior class are termed as Behaviors. The methods and properties of the behaviours are inserted to the component to which it is attached. Behaviors also respond to the events that are triggered by the component.

How to define Yii Behaviors?

Step 1 − A behaviour is defined by extending the yiibaseBehavior class.

The behaviour with one property (prop1) and one method (myFunction) is defined by the above code. When this behaviour is attached to the component, the component will also get the prop1 property and the myFunction method.

The component to which the behavior is attached to, can be accessed by using the yiibaseBehavior::$owner property.

Step 2 – A behavior can respond to the component event by overriding the yiibaseBehavior::events() method.

Step 3 − To attach a behavior, override the behaviors() method of the component class.

Step 4 − To detach a behavior, call the yiibaseComponent::detachBehavior() method.

To show behaviors in action, data is needed.

Preparing the DB

Step 1 − A new database is created. Database can be prepared in the following two ways.

  • In the terminal run mysql -u root –p.
  • Create a new database via CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci;

Step 2 − The database connection is configured in the config/db.php file. The following configuration is for the system used currently.

Step 3 − Inside the root folder run ./yii migrate/create test_table. This command will create a database migration for managing our DB. The migration file should appear in the migrations folder of the project root.

Step 4 − The migration file m160106_163154_test_table.php is modified by the code:

A user table is created with the above migration with the fields: id, name, and email and a few demo users are added.

Step 5 −Inside the project root run./yii migrate to apply the migration to the database.

Step 6 – A model is created for our user table. For the sake of simplicity, use the Gii code generation tool. Open up the url: http://localhost:8080/index.php?r=gii. Then, click the “Start” button under the “Model generator” header. Fill in the Table Name (“user”) and the Model Class (“MyUser”), click the “Preview” button and finally, click the “Generate” button

Create Model

The MyUser model should appear in the models directory.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Yii Topics