2016-07-26 5 views
1

現在、私はSymfony2を使って新しいプロジェクトを進めています。 http://www.example.com/dog/bark/loudlySymfony2はルーティングなしでコントローラのアクションを直接呼び出します

そしてルートを記述することなく、framworkはDogControllerのbarkActionを呼び出し、それに引数を渡すloudly:Zendの出身 私は本当にのようなURLに直接コントローラとそのアクションを呼び出すことができるという楽しみました。

残念ながら、Symfony2はこれをやりたいとは思われませんでした。私はいくつかのグーグル・グーグルでドキュメントを見ましたが、無駄でした。 私はこれを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 
関連する問題