2016-07-26 50 views
1

目前我正在使用Symfony2的新项目。 从Zend的产品我真的很喜欢能够直接在URL调用控制器和他们的行动,像这样:http://www.example.com/dog/bark/loudlySymfony2直接调用控制器没有路由的动作

然后,而无需编写了一个途径,framwork会召唤DogController的barkAction并把它传递参数loudly

不幸的是,Symfony2似乎并不喜欢这样做,我做了一些Google搜索,查看了文档,但它是无济于事。 我很想知道如何在Symfony2中实现这一点。

回答

0

您可以创建自己的路由装载程序,如解释in the documentation

然后使用ReflexionClass列出您的操作。

您也可以重复每个控制器上DirectoryIterator

例子:

// src/AppBundle/Routing/ExtraLoader.php 
namespace AppBundle\Routing; 

use Symfony\Component\Config\Loader\Loader; 
use Symfony\Component\Routing\Route; 
use Symfony\Component\Routing\RouteCollection; 

class ExtraLoader extends Loader 
{ 
    private $loaded = false; 

    public function load($resource, $type = null) 
    { 
     if (true === $this->loaded) { 
      throw new \RuntimeException('Do not add the "extra" loader twice'); 
     } 

     $routes = new RouteCollection(); 

     $controllerName = 'Default'; 

     $reflexionController = new \ReflectionClass("AppBundle\\Controller\\".$controllerName."Controller"); 

     foreach($reflexionController->getMethods() as $reflexionMethod){ 
      if($reflexionMethod->isPublic() && 1 === preg_match('/^([a-ZA-Z]+)Action$/',$reflexionMethod->getName(),$matches)){ 
       $actionName = $matches[1]; 
       $routes->add(
        strtolower($controllerName) & '_' & strtolower($actionName), // Route name 
        new Route(
         strtolower($controllerName) & '_' & strtolower($actionName), // Path 
         array('_controller' => 'AppBundle:'.$controllerName.':'.$actionName), // Defaults 
         array() // requirements 
        ) 
       ); 
      } 
     } 

     $this->loaded = true; 

     return $routes; 
    } 

    public function supports($resource, $type = null) 
    { 
     return 'extra' === $type; 
    } 
} 
+0

这就是我要找的谢谢。 – User9123

0

每个框架都有它自己的特点。对我来说,下面的粗略示例是最简单的方法,因此您应该可以通过http://www.my_app.com/dog/bark/loudly

将其定义为服务。 How to Define Controllers as Services

namespace MyAppBundle\Controller\DogController; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 

/** 
* @Route("/dog", service="my_application.dog_controller") 
*/ 
class DogController extends Controller 
{ 
    /** 
    * @Route("/bark/{how}") 
    */ 
    public function barkAction($how) 
    { 
     return new Response('Dog is barking '.$how); 
    } 
} 

服务定义

services: 
    my_application.dog_controller: 
     class: MyAppBundle\Controller\DogController 
相关问题