Symfony annotations構文

1919 ワード

1、@Route
このコメントは、Webサイト/パスとindexActionのマッピングを定義し、ユーザーが/パスにアクセスするとindexActionメソッドを実行します.
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class PostController extends Controller{
    /**     
    * @Route("/")     
    */
    public function indexAction()
    {
        // ...
    }
}

{id}はパラメータであり、requirementsはidを数値のみとして定義し、defaultsはデフォルト変数fooと値barを定義します.
/** 
* @Route("/{id}", requirements={"id" = "\d+"}, defaults={"foo" = "bar"}) 
*/
public function showAction($id)
{
}

アクセス/パスと/{id}はいずれもshowActionメソッドを実行し、アクセス/パスの場合、id=1を付けてshowActionメソッドに値を渡す
/** 
* @Route("/", defaults={"id" = 1}) 
* @Route("/{id}")
*/
public function showAction($id)
{
}

パスと名前を定義し、$this->generateUrl('blog_home')を定義すると、homeActionメソッドにアクセスするURLが作成されます.
/** 
* @Route("/", name="blog_home") 
*/
public function homeAction(){
}

最初のコメント@Route("/blog")は、パス接頭辞を設定します.この定義の後
showActionメソッドにアクセスするパスは、実際には/blog/{id}
/** 
* @Route("/blog") 
*/
class PostController extends Controller{
    /**
    * @Route("/{id}")
    */
    public function showAction($id)
    {
    }
 }

@Methodがサポートするリクエストのタイプを設定
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/** 
* @Route("/blog") 
*/
class PostController extends Controller{
    /**     
    * @Route("/edit/{id}")     
    * @Method({"GET", "POST"})     
    */
    public function editAction($id)
    {
    }
}

コントローラをサービスとして定義すると、コンテナで使用できます.
/** 
* @Route(service="my_post_controller_service") 
*/
class PostController extends Controller{
    // ...
}