yavin/symfony-init-controller

在每次操作之前运行初始化控制器方法

v0.4 2016-05-16 17:32 UTC

This package is auto-updated.

Last update: 2024-08-28 01:40:33 UTC


README

Build Status

添加在控制器中每次操作前执行 init 方法的功能。基于 这个答案

示例

class SampleController extends Controller implements InitControllerInterface
{
    protected $page;

    public function init(Request $request)
    {
        if ($request->get('redirect') == 1) {
            return $this->redirect('http://example.com');
        }

       $this->page = $request->get('page');
    }

    public function indexAction()
    {
        //some action code
    }
}

安装

  1. 在 composer.json 中添加库

    "yavin/symfony-init-controller": "0.3"

    并运行命令

    composer update yavin/symfony-init-controller
    
  2. 在您的包服务文件 Resources/config/services.xml 中添加服务

    <service class="Yavin\Symfony\Controller\InitControllerSubscriber">
        <tag name="kernel.event_subscriber"/>
    </service>

    或者如果您有 services.yml

    services:
        symfony.controller.subscriber.init:
            class: Yavin\Symfony\Controller\InitControllerSubscriber
            tags:
                - { name: kernel.event_subscriber }
  3. 然后在您想要有初始化方法的控制器中实现 InitControllerInterface

    namespace Acme\DemoBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\Request;
    use Yavin\Symfony\Controller\InitControllerInterface;
    
    class SampleController extends Controller implements InitControllerInterface
    {
        protected $page;
    
        public function init(Request $request)
        {
            //init method could return response, for example redirect
            if ($request->get('redirect') == 1) {
                return $this->redirect('http://example.com');
            }
    
            $this->page = $request->get('page');
        }
    
        public function indexAction()
        {
            //...
        }
    
        public function otherAction()
        {
            //...
        }
    }