Argument resolver

Controller methods can inject properties if it is type-hinted correctly:

  • Post $post for single post page

  • Term $term and PostCollection $posts for archive page

  • User $author and PostCollection $posts for author archive page

  • Blog $blog

The resolvers take care of validating the controller callable and its arguments. In case of a problem, it throws an exception with a nice message explaining the problem.

This is also relevant to handle 404 error : see the guide Better error pages

Exemple

<?php

namespace App\Controller;

use Metabolism\WordpressBundle\Entity\Post;
use Metabolism\WordpressBundle\Entity\PostCollection;
use Metabolism\WordpressBundle\Entity\Term;
use Metabolism\WordpressBundle\Entity\User;
use Metabolism\WordpressBundle\Entity\Blog;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class BlogController extends AbstractController
{
	public function homeAction(Post $post, Blog $blog)
	{
		if( $blog->is_admin )
			return $this->render('admin.html.twig', ['post'=>$post]);

		return $this->render('home.html.twig', ['post'=>$post]);
	}	
	
	public function pageAction(Post $post)
	{
		return $this->render('single.html.twig', ['post'=>$post]);
	}

	public function searchAction(PostCollection $posts, $search)
	{
        	return $this->render('search.html.twig', [
            		'search_query'=>$search,
		        'posts'=>$posts
        	]);
	}

	public function categoryAction(Term $term, PostCollection $posts)
	{
        	return $this->render('archive.html.twig', [
            		'posts'=>$posts,
            		'term'=>$term
	       	]);
	}

	public function authorAction(User $user, PostCollection $posts)
	{
        	return $this->render('author-archive.html.twig', [
            		'posts'=>$posts,
            		'author'=>$user
        	]);
	}
}

Last updated