cakephp3 load plugin for special prefix

主宰稳场 提交于 2020-01-07 06:43:01

问题


I have Cakephp 3 application and i want to load this plugin and the event listener below it just for admin prefix. ( not the entire project ) .

how can i achive this?

this is my

config/bootstrap.php

where i load this plugin . (I load these at end of the file )

...

Plugin::load('Josegonzalez/Upload');

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());

i want these to line only run on admin prefix


回答1:


You can't conditionally run code based upon routing inside boostrap.php as the routing configuration for you app hasn't been loaded yet.

You'll have to do it old school style and use $_SERVER['REQUEST_URI'].

$url = $_SERVER['REQUEST_URI'];
$admin = '/admin/';
if(substr($url, 0, strlen($admin)) === $admin) {
    Plugin::load('Josegonzalez/Upload');
    \Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());
}

Updated

Your plugin should have it's own bootstrap file. Which contains

Upload/config/bootstrap.php:

\Cake\Event\EventManager::instance()->on(new \App\Controller\Event\AppEventListener());

The app's bootstrap then tells CakePHP to include the bootstrap when loading the plugin.

App/config/bootstrap.php:

    Plugin::load('Josegonzalez/Upload', ['bootstrap' => true]);

You shouldn't conditionally load your plugin.

I think you are searching for authentication on requests to your plugin. You want to limit use of your plugin only to authorized administrators. That is not a plugin issue. It is an authentication issue and you should be using the Authentication component in your plugin to verify the request is valid, and that the current user is an administrator.




回答2:


Quoting cakephp plugin docs https://book.cakephp.org/3.0/en/plugins.html#plugin-routes

You can also load plugin routes in your application’s routes list. Doing this provides you more control on how plugin routes are loaded and allows you to wrap plugin routes in additional scopes or prefixes.

So you can do

  Router::scope('/', function ($routes) {
       // Connect other routes.
        $routes->scope('/admin', function ($routes) {
        $routes->loadPlugin('Josegonzalez/Upload');
       });
       });

For your event listener, load it inside plugin bootstrap configuration

    // inside plugin bootstra.php
    \Cake\Event\EventManager::instance()->on(new 
     \App\Controller\Event\AppEventListener());


来源:https://stackoverflow.com/questions/47333733/cakephp3-load-plugin-for-special-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!