Symfony Basics Cheatsheet

Tags : php symfony

Routing (from the doc)
/**
 * @Route("/")
 */

// Example
@Route("/post/edit/{id}", name="post_edit",
            methods={"GET","POST"})

// Requirements
@Route("/blog/{page<\d+>}", name="blog_list")
@Route("/blog/{page}", name="blog_list", 
            requirements={"page"="\d+"})

// Localized Route
@Route({"fr": "/a-propos", 
        "en": "/about-us"}, name="about_us")

// Loaded Example
@Route("/posts/{_locale}/{year}/{slug}.{_format}",
            defaults={"_format": "html"},
            requirements={
                "_locale": "en|fr",
                "_format": "html|rss",
                "year": "\d+"
            })

// Debug
$ php bin/console debug:router
Request
// Get GET params
$request->query->all();
$request->query->get(‘some_param’);

// Get POST params
$request->request->all();

// For JSON data :
$request->getContent();
Response
return $this->redirectToRoute('article_show');

return $this->redirectToRoute('article_show', ['id' => 10]);
Usefull Controller methods
// Generate url
$url = $this->generateUrl('blog_show',
                ['slug' => 'my-blog-post']);
Namespaces
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

// Request / Response
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;

// Annotations
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

// Exceptions
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

// Misc
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Psr\Log\LoggerInterface;
Cache annotations
// use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;

@Cache(expires="tomorrow")
@Cache(smaxage="15")
@Cache(maxage="15")
@Cache(maxstale="15")
@Cache(staleWhileRevalidate="15")
@Cache(staleIfError="15")
@Cache(vary={"Cookie"})
@Cache(public=true)
@Cache(lastModified="post.getUpdatedAt()")
@Cache(Etag="post.getId() ~ post.getUpdatedAt().getTimestamp()")
@Cache(mustRevalidate=true)