在 Laravel 4 中注册观察者的确切位置 [英] Exact place to register observer in Laravel 4
问题描述
当为模型观察者使用单独的类时,我应该在哪里注册观察者?文档说要调用 User::observe(new UserObserver);
,但我不确定这样做的最佳位置在哪里.
When using a separate class for a model observer, where exactly should I register the observer? The documentation says to call User::observe(new UserObserver);
but I’m not sure where the best place to do this would be.
https://laravel.com/docs/5.4/eloquent#observers
推荐答案
由于观察者只是您正在收听的事件的集合,所以我想说的是将它放在 Laravel 建议您放置单个事件的地方:在 上模型本身的引导
方法.
Since an observer is just a collection of events you are listening to, I'd say place it where Laravel suggests you place individual events: on the boot
method of the model itself.
class User extends Eloquent
{
public static function boot()
{
parent::boot();
User::observe(new UserObserver);
}
}
将 UserObserver
类放在哪里更灵活一点,取决于它最终的复杂程度.
Where to put the UserObserver
class is a little more flexible and depends on how complex it will end up being.
如果您可以在每次应用程序运行时加载它,请创建一个 app/observers.php
文件,然后将其放在您的 app/start/global.php 的末尾代码>:
If you can bare having it load every time the app runs, create an app/observers.php
file, then put this at the end of your app/start/global.php
:
require app_path().'/observers.php';
或者,您可以使用 composer 自动加载该文件,方法是附加您的 composer.json
:
Alternatively, you can use composer to autoload that one file, by appending your composer.json
:
{
"autoload": {
"classmap": [
//...
],
"files": [
"app/observers.php"
]
}
}
对于更复杂的观察者
如果你打算有很多不同的观察者,我会说创建你自己的命名空间,让 Laravel/Composer 为你自动加载.为此,创建一个像 app/MyNamespace/Observers
这样的文件夹,然后将每个观察者文件放入其中(每个文件的名称都与类完全相同——即 UserObserver.php
>).
For more complex observers
If you plan to have many different observers, I'd say create your own namespace and let Laravel / Composer do the autoloading for you. In order to do that, create a folder like app/MyNamespace/Observers
, then place each observer file inside of it (each named exactly like the class -- i.e. UserObserver.php
).
您的 UserObserver.php
类现在应如下所示:
Your UserObserver.php
class should now look like this:
<?php
namespace MyNamespaceObservers;
class UserObserver
{
public function saving($model)
{
// ...
}
public function saved($model)
{
// ...
}
}
而且你必须在使用它时声明完整的类:
And you'll have to declare the full class whenever you are using it:
User::observe(new MyNamespaceObserversUserObserver);
或者:
use MyNamespaceObserversUserObserver;
class User extends Eloquent
{
public static function boot()
{
parent::boot();
User::observe(new UserObserver);
}
}
最后,编辑您的 composer.json
并添加您的命名空间以遵循 PSR-0 自动加载:
Finally, edit your composer.json
and add your namespace to follow PSR-0 autoloading:
{
"autoload": {
"classmap": [
//...
],
"psr-0": [
"MyNamespace": "app/"
]
}
}
PS:编辑完composer.json
后不要忘记运行composer dump-autoload
.
PS: Don't forget to run composer dump-autoload
after editing composer.json
.
这篇关于在 Laravel 4 中注册观察者的确切位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!