namespace app\components; use yii\base\Behavior; class MyBehavior extends Behavior { private $_prop1; public function getProp1() { return $this->_prop1; } public function setProp1($value) { $this->_prop1 = $value; } public function myFunction() { // ... } }
namespace app\components; use yii\db\ActiveRecord; use yii\base\Behavior; class MyBehavior extends Behavior { public function events() { return [ ActiveRecord::EVENT_AFTER_VALIDATE => 'afterValidate', ]; } public function afterValidate($event) { // ... } }
namespace app\models; use yii\db\ActiveRecord; use app\components\MyBehavior; class MyUser extends ActiveRecord { public function behaviors() { return [ // anonymous behavior, behavior class name only MyBehavior::className(), // named behavior, behavior class name only 'myBehavior2' => MyBehavior::className(), // anonymous behavior, configuration array [ 'class' => MyBehavior::className(), 'prop1' => 'value1', 'prop2' => 'value2', 'prop3' => 'value3', ], // named behavior, configuration array 'myBehavior4' => [ 'class' => MyBehavior::className(), 'prop1' => 'value1' ] ]; } }
$component->detachBehavior('myBehavior');
在終端執行 mysql -u root –p
登入資料後,通過執行 CREATE DATABASE mystudy CHARACTER SET utf8 COLLATE utf8_general_ci; 建立一個新的資料庫;
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host = localhost;dbname = mystudy', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]; ?>
第3步 - 在專案根檔案夾執行:yii migrate/create test_table 。此命令將用於建立管理資料庫資料庫遷移。 migrations檔案會出現在專案的根的 migrations 檔案夾中。
<?php use yii\db\Schema; use yii\db\Migration; class m160529_014611_test_table extends Migration { public function up() { $this->createTable("user", [ "id" => Schema::TYPE_PK, "name" => Schema::TYPE_STRING, "email" => Schema::TYPE_STRING, ]); $this->batchInsert("user", ["name", "email"], [ ["User1", "[email protected]"], ["User2", "[email protected]"], ["User3", "[email protected]"], ["User4", "[email protected]"], ["User5", "[email protected]"], ["User6", "[email protected]"], ["User7", "[email protected]"], ["User8", "[email protected]"], ["User9", "[email protected]"], ["User10", "[email protected]"], ["User11", "[email protected]"], ]); } public function down() { //$this->dropTable('user'); } } ?>
第6步-現在,我們需要為user表建立模型。為了簡便起見,我們將使用GII程式碼生成工具。在瀏覽器中開啟 url: http://localhost:8080/index.php?r=gii 。
然後,點選 「Model generator」 下的 「Start」按鈕。 填寫表名(「user」)和模型類(「MyUser」),單擊「Preview」按鈕,最後點選 「Generate」 按鈕。