Rendering Templates
If you're serving HTML, you'll want to render a template. The render()
method renders a template and puts that content into a Response
object for you:
Copy return $this -> render ( 'home.html.twig' , [ 'post' => $post] ) ;
Templating and Twig are explained more in the Creating and Using Templates article .
Fetching Services
Symfony comes packed with a lot of useful classes and functionalities, called services . These are used for rendering templates, sending emails, querying the database and any other "work" you can think of.
If you need a service in a controller, type-hint an argument with its class (or interface) name. Symfony will automatically pass you the service you need:
Copy use Psr \ Log \ LoggerInterface ;
use Symfony \ Component \ HttpFoundation \ Response ;
public function homeAction ( Post $post , LoggerInterface $logger)
{
$logger -> info ( 'We are logging!' ) ;
// ...
}
The Wordpress Bundle adds two services : PaginationService and BreadcrumbService
Copy /**
* @param PostCollection $posts
* @params PostRepository $postRepository
* @param PaginationService $paginationService
* @param BreadcrumbService $breadcrumbService
* @return Response
*/
public function articleThematicAction(PostCollection $posts, PostRepository $postRepository, PaginationService $paginationService, BreadcrumbService $breadcrumbService)
{
$context = [ 'posts' => $posts];
if ( $page = $postRepository -> findByState ( 'news_landing' ) ){
$context[ 'breadcrumb' ] = $breadcrumbService -> build ( [ 'data' => [[
'title' => $page -> getTitle (),
'link' => $page -> getLink ()
]]] ) ;
}
$context[ 'pagination' ] = $paginationService -> build () ;
return $this -> render ( 'page/term.twig' , $context ) ;
}
get_page_by_state
is a new function available in the WP Steroids plugin, see docs
Fetching Repository
The Wordpress Bundle adds three repository : PostRepository , TermRepository and UserRepository designed to mimic Doctrine Repository way to fetch object from database.
Internally, it still uses Wordpress native functions WP_Query, WP_Term_Query and WP_User_Query to ensure plugins compatibility
Copy /**
* @param Post $post
* @param PostRepository $postRepository
* @return Response
*/
public function pageAction ( Post $post , PostRepository $postRepository)
{
$context = [
'post' => $post ,
'related' => $postRepository->findBy(['post_type'=>'page', 'post_parent' => $post->parent, 'post__not_in' => [$post->ID] ],null, 4)
];
return $this -> render ( 'page.html.twig' , $context ) ;
}