繁体   English   中英

如何在 Symfony2 控制器中获取动作名称?

[英]How can I get the action name in a Symfony2 controller?

有没有办法在 Symfony2 控制器中获取动作的名称?

public function createAction(Request $request, $title) {

    // Expected result: create
    $name = $this->getActionName();

}

用:

$request->attributes->get('_controller');
// will get yourBundle\Controller\yourController::CreateAction

$params = explode('::',$request->attributes->get('_controller'));
// $params[1] = 'createAction';

$actionName = substr($params[1],0,-6);
// $actionName = 'create';

我找到了这个片段(这里):

$matches    = array();
$controller = $this->getRequest()->attributes->get('_controller');
preg_match('/(.*)\\\(.*)Bundle\\\Controller\\\(.*)Controller::(.*)Action/', $controller, $matches);

这似乎是一种很有前途的方法。 这个正则表达式实际上不起作用。 但是使用 strstr()获取操作名称并不难。 作品!

并返回(见示例

Array
(
    [0] => Acme\MyBundle\Controller\MyController::myAction
    [1] => Acme
    [2] => My
    [3] => My
    [4] => my
)

如果输入是Acme\\MyBundle\\Controller\\MyController::myAction

现在,我将它与 Symfony 2.8(和 Symfony3)一起使用:

<?php

namespace Company\Bundle\AppBundle\Component\HttpFoundation;

use Symfony\Component\HttpFoundation\Request as BaseRequest;

/**
 * Request shortcuts.
 */
class Request extends BaseRequest
{
    /**
     * Extract the action name.
     *
     * @return string
     */
    public function getActionName()
    {
        $action = $this->get('_controller');
        $action = explode('::', $action);

        // use this line if you want to remove the trailing "Action" string
        //return isset($action[1]) ? preg_replace('/Action$/', '', $action[1]) : false;

        return $action[1];
    }

    /**
     * Extract the controller name (only for the master request).
     *
     * @return string
     */
    public function getControllerName()
    {
        $controller = $this->get('_controller');
        $controller = explode('::', $controller);
        $controller = explode('\\', $controller[0]);

        // use this line if you want to remove the trailing "Controller" string
        //return isset($controller[4]) ? preg_replace('/Controller$/', '', $controller[4]) : false;

        return isset($controller[4]) ? $controller[4] : false;
    }
}

要使用这个自定义请求类,你必须在你的web/app*.php控制器中“使用”它:

use Company\Bundle\AppBundle\Component\HttpFoundation\Request;
// ...
$request = Request::createFromGlobals();
// ...

然后在您的控制器中:

class AppController extends Controller
{
    /**
     * @Route("/", name="home_page")
     * @Template("")
     *
     * @return array
     */
    public function homePageAction(Request $request)
    {
        $controllerName = $request->getControllerName();
        $actionName = $request->getActionName();

        dump($controllerName, $actionName); die();

        // ...
    }

将输出:

AppController.php on line 27:
"AppController"
AppController.php on line 27:
"homePageAction"

您还可以通过RequestStack服务访问这些功能:

class MyService
{
    /**
     * @param RequestStack $requestStack
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function myService()
    {
        $this->controllerName = $this->requestStack->getMasterRequest()->getControllerName();
        $this->actionName = $this->requestStack->getMasterRequest()->getActionName();

        // ...
    }

如果您使用 Controller as a Service,则架构会有所不同:

$request->attributes->get('_controller'); 将返回“service_id:createAction”

两种模式的可能解决方案:

$controller = $request->attributes->get('_controller');
$controller = str_replace('::', ':', $controller);
list($controller, $action) = explode(':', $controller);

在所有版本的 symfony 中,没有 $request 或容器、服务或其他任何东西...,直接在您的方法中

public function myMethod(){
   $methodName = __METHOD__;
   return $methodName;
}

// return App\Controller\DefaultController::myMethod

public function mySecondMethod(){
   $methodName = explode('::', __METHOD__);
   return $methodName[1];
}

// return mySecondMethod

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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