前面的幾篇文章
本系列文章的目的就是脫離laravel環境使用Eloquent, 因為它好用。
本系列文章所有代碼均測試通過。 Eloquent版本:5.4.27
本文的目的是使用事件, 即鉤子函數, 用於保存前後, 修改資料模型前後, 刪除前後。
下面的代碼假定使用了一個表test2。
主要是4個檔, 名字都可以自己改。 路徑也可以自己改, 只要改namespace即可。
1)User是模型檔, 裡面啥都沒有, 從我目前測試結果看, 也無法在類裡面寫監聽。
2)程式主文件。 Ill.php
3)sql日誌事件檔。 SqlListener
4)User觀察者類。 需被手動註冊到User類上面。
檔層次:
app
- control
- Ill.php
- model
- SqlListener.php
- User.php
- UserObserver.php
模型檔User.php
errinfo = $info; } public function get_errinfo { return $this->errinfo ; } }觀察者類UserObserver.php
user) set_errinfo("creating: 用戶名至少兩個字元"); return false; } } /** * 添加用戶鉤子 * * @param User $user * @return void */ public function created(User $user) { echo "in UserObserver.created:". $user->id .""; } /** * 修改用戶鉤子 * * @param User $user * @return void */ public function updated(User $user) { echo "in UserObserver.updated:". $user->id ."
"; } }
sql日誌檔
"; } } }
主程序
addConnection ( [ 'driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'test1', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '' ] ); $capsule->setAsGlobal ; $capsule->bootEloquent ; // 設置sql日誌監聽 $capsule->setEventDispatcher ( new SqlListener ); // User模型類加鉤子 User::setEventDispatcher ( new Dispatcher ); User::observe ( \app\model\UserObserver::class ); // 這句話單純測試log $users = $capsule::select ( 'SELECT * FROM test2 limit 1' ); // 下麵幾句測log + 鉤子 $user = new User ; $user->user = '11'; $result = $user->save ; // 新模型添加 $user->user = '22'; $result = $user->save ; // 已經不是新模型, 是已存在模型, 所以是修改。 $user = new User ; $user->user = '3'; // 故意填寫過短的用戶名 $result = $user->save ; // 注意這裡!因為創建模型前置函數creating返回假。 if (! $result) { echo $user->get_errinfo . ""; } echo 'all ok!'; } }
下面是流覽器輸出結果
log: SELECT * FROM test2 limit 1 log: insert into `test2` (`user`) values ('11') in UserObserver.created:120 log: update `test2` set `user` = '22' where `id` = '120' in UserObserver.updated:120 creating: 用戶名至少兩個字元 all ok!總結:總的來說, 還是很好用的。 但是, 手動註冊觀察者的代碼需要封裝到函數裡, 在php應用程式的公共起始檔裡被調用。