简体   繁体   中英

Check if event is coming from a model inside a plugin?

I need all models inside a custom CakePHP plugin to use a database prefix. I'm trying to use an event, as suggested by @lorenzo .

EventManager::instance()->on('Model.initialize', function ($event) {
    $instance = $event->subject();
    $instance->table('prefix_' . $instance->table());
});

I'm getting several callbacks from my plugin model as well as DebugKit models, and potentially it could be other models in the application.

Is there a way to tell if a given $event is coming from within a plugin?

I have checked $event->getSubject() and it contains the corresponding Table class. The only feasible way I could come up with is to check some properties for the plugin name.

  • $event->getSubject()->getRegistryAlias() is ExamplePlugin.Posts
  • $event->getSubject()->getEntityClass() is ExamplePlugin\Model\Entity\Post

I could check if either starts with ExamplePlugin . Is there a better way?

The fact that basically any PHP namespace can be a plugin means you could do something like that:

EventManager::instance()->on('Model.initialize', function (\Cake\Event\EventInterface $event) {
    /** @var \Cake\ORM\Table $object */
    $object = $event->getSubject();
    $tableClassName = get_class($object);
    $isApp = str_starts_with($tableClassName, 'App');
});

Because your main app's namespace will always begin with App

This of course wouldn't distinguish between your private plugins which are located in plugins and plugins which are installed via composer and therefore live in the vendor directory.

But you could introduce a name prefix to all your private plugins so you can easily distinguish them from any other plugins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM