This tutorial has a new version, check it out!

Routes, Controllers, Pages, oh my!

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

Let's create our first page! Actually, this is the main job of a framework: to give you a route and controller system. A route is configuration that defines the URL for a page and a controller is a function that we write that actually builds the content for that page.

And right now... our app is really small! Instead of weighing down your project with every possible feature you could ever need - after all, we're not in zero-gravity yet - a Symfony app is basically just a small route-controller system. Later, we'll install more features when we need them, like a warp drive! Those always come in handy. Adding more features is actually going to be pretty awesome. More on that later.

First Route & Controller

Open your app's main routing file: config/routes.yaml:

#index:
# path: /
# controller: App\Controller\DefaultController::index

Hey! We already have an example! Uncomment that. Ignore the index key for now: that's the internal name of the route, but it's not important yet.

This says that when someone goes to the homepage - / - Symfony should execute an index() method in a DefaultController class. Change this to ArticleController and the method to homepage:

index:
path: /
controller: App\Controller\ArticleController::homepage

And... yea! That's a route! Hi route! It defines the URL and tells Symfony what controller function to execute.

The controller class doesn't exist yet, so let's create it! Right-click on the Controller directory and go to "New" or press Cmd+N on a Mac. Choose "PHP Class". And, yes! Remember that Composer setup we did in Preferences? Thanks to that, PhpStorm correctly guesses the namespace! The force is strong with this one... The namespace for every class in src/ should be App plus whatever sub-directory it's in.

Name this ArticleController:

<?php
namespace App\Controller;
... lines 4 - 6
class ArticleController
{
... lines 9 - 12
}

And inside, add public function homepage():

... lines 1 - 2
namespace App\Controller;
... lines 4 - 6
class ArticleController
{
public function homepage()
{
... line 11
}
}

This function is the controller... and it's our place to build the page. To be more confusing, it's also called an "action", or "ghob" to its Klingon friends.

Anyways, we can do whatever we want here: make database queries, API calls, take soil samples looking for organic materials or render a template. There's just one rule: a controller must return a Symfony Response object.

So let's say: return new Response(): we want the one from HttpFoundation. Give it a calm message: OMG! My first page already! WOOO!:

... lines 1 - 2
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
class ArticleController
{
public function homepage()
{
return new Response('OMG! My first page already! WOOO!');
}
}

Ahem. Oh, and check this out: when I let PhpStorm auto-complete the Response class it added this use statement to the top of the file automatically:

... lines 1 - 4
use Symfony\Component\HttpFoundation\Response;
... lines 6 - 14

You'll see me do that a lot. Good job Storm!

Let's try the page! Find your browser. Oh, this "Welcome" page only shows if you don't have any routes configured. Refresh! Yes! This is our page. Our first of many.

Annotation Routes

That was pretty easy, but it can be easier! Instead of creating our routes in YAML, let's use a cool feature called annotations. This is an extra feature, so we need to install it. Find your open terminal and run:

composer require annotations

Interesting... this annotations package actually installed sensio/framework-extra-bundle. We're going to talk about how that works very soon.

Now, about these annotation routes. Comment-out the YAML route:

#index:
# path: /
# controller: App\Controller\ArticleController::homepage

Then, in ArticleController, above the controller method, add /**, hit enter, clear this out, and say @Route(). You can use either class - but make sure PhpStorm adds the use statement on top. Then add "/":

... lines 1 - 4
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
... lines 6 - 7
class ArticleController
{
/**
* @Route("/")
*/
public function homepage()
{
... line 15
}
}

Tip

When you auto-complete the @Route annotation, be sure to choose the one from Symfony\Component\Routing - the one we chose is now deprecated. Both work the same.

That's it! The route is defined right above the controller, which is why I love annotation routes: everything is in one place. But don't trust me, find your browser and refresh. It's a traaaap! I mean, it works!

Tip

What exactly are annotations? They're PHP comments that are read as configuration.

Fancy Wildcard Routes

So what else can we do with routes? Create another public function called show(). I want this page to eventually display a full article. Give it a route: @Route("/news/why-asteroids-taste-like-bacon"):

... lines 1 - 4
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
... lines 6 - 7
class ArticleController
{
... lines 10 - 17
/**
* @Route("/news/why-asteroids-taste-like-bacon")
*/
public function show()
{
... line 23
}
}

Eventually, this is how we want our URLs to look. This is called a "slug", it's a URL version of the title. As usual, return a new Response('Future page to show one space article!'):

... lines 1 - 4
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class ArticleController
{
... lines 10 - 17
/**
* @Route("/news/why-asteroids-taste-like-bacon")
*/
public function show()
{
return new Response('Future page to show one space article!');
}
}

Perfect! Copy that URL and try it in your browser. It works... but this sucks! I don't want to build a route and controller for every single article that lives in the database. Nope, we need a route that can match /news/ anything. How? Use {slug}:

... lines 1 - 7
class ArticleController
{
... lines 10 - 17
/**
* @Route("/news/{slug}")
*/
public function show($slug)
{
... lines 23 - 26
}
}

This route now matches /news/ anything: that {slug} is a wildcard. Oh, and the name slug could be anything. But whatever you choose now becomes available as an argument to your "ghob", I mean your action.

So let's refactor our success message to say:

Future page to show the article

And then that slug:

... lines 1 - 7
class ArticleController
{
... lines 10 - 17
/**
* @Route("/news/{slug}")
*/
public function show($slug)
{
return new Response(sprintf(
'Future page to show the article: "%s"',
$slug
));
}
}

Try it! Refresh the same URL. Yes! It matches the route and the slug prints! Change it to something else: /why-asteroids-taste-like-tacos. So delicious! Go back to bacon... because... ya know... everyone knows that's what asteroids really taste like.

And... yes! We're 3 chapters in and you now know the first half of Symfony: the route & controller system. Sure, you can do fancier things with routes, like match regular expressions, HTTP methods or host names - but that will all be pretty easy for you now.

It's time to move on to something really important: it's time to learn about Symfony Flex and the recipe system. Yum!

Leave a comment!

  • 2020-01-31 Diego Aguiar

    Hmm, your file looks correct. It makes think that you are not running on PHP7 in your web server (You may have installed PHP7 only to the CLI). Check the phpinfo of your webserver to double check what I'm saying. If that's the case, then you now know what to do :)

    Cheers!

  • 2020-01-31 Nick Smith

    I can't get it to paste into code, so I'm linking a screenshot: https://imgur.com/a/07J6TBh

    Does that help?

    Thanks again!

  • 2020-01-31 Diego Aguiar

    > Also, I think your "cheers" being in code format means there's something there that I'm not seeing?

    Yeah you are right! Disqus messed it up - I just fixed it

    If you still have this problem. Could you show me your entire index.php file please?

    > Also thank you for being here to help, and being so responsive to everyone. Looking forward to being part of this community. :)

    You are welcom man :)

  • 2020-01-30 Nick Smith

    Thanks for the reply Diego Aguiar!

    Unfortunately (fortunately?) I am, I had to update it from 5.6 to 7.1.3 to run Composer. Also, I think your "cheers" being in code format means there's something there that I'm not seeing?

    Also thank you for being here to help, and being so responsive to everyone. Looking forward to being part of this community. :)

  • 2020-01-30 Diego Aguiar

    Hey Nick Smith

    At first sight I think you are not running on PHP 7. The operator ?? was introduce in PHP 7. If that's not the case, check the first line of your file, probably you have something like this "<"??php (had to wrap it with double quotes so Disqus can render it)

    Cheers!

  • 2020-01-29 Nick Smith

    I'm at "omg my first page already" and I'm following along/started the project by myself, and I have this error loading index.php:

    Parse error: syntax error, unexpected '?' in C:\www\eds-www\tuts\the_spacebar\public\index.php on line 15

    Here's line 15-17 of index.php:

    if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
    }

    What have I fouled up?

  • 2020-01-28 Diego Aguiar

    Hey Kutay Deril

    What you mean by only client and env? Did you download the course code or did you started the project by yourself?

    Cheers!

  • 2020-01-27 Kutay Deril

    In 3:00 Chapter 3 I only have client and env. Why it is different?

  • 2019-11-04 Turchese

    Hi everyone! If you have Symfony version 4.3 to use the annotations you need to insert this in your BlogController:
    use Symfony\Component\Routing\Annotation\Route;

    They changed the directory, that's why so many of you are receiving error messages.

    Tip: To easily configure a new controller you can use the terminal by writing
    php bin/console make:controller

    Hope it helped!

  • 2019-09-09 Diego Aguiar

    Ohh, I see. Then, what you can do is to create a base abstract class that all your controllers with inherit and add all of your common logic/methods on it.

    Tip: A controller should not *own* too much logic (and even less if it's business logic), so if you find yourself adding a lot of code to a controller that's a good hint that you may need a service class.

    Cheers!

  • 2019-09-07 Avraham Markov

    Hey Diego Aguiar
    I try to avoid code repetition.
    The simple option I have is to create 2 ( or more) actions in Controller,
    so actions make common stuff and some specific stuff for each.
    I thought about template design pattern..
    Can you please be more detailed about the base class and the structure to organize it?

    Thanks!

    p.s.
    I thought about custom actions inside MyController,
    how is it?

    public class MyController
    {

    /**
    *@Route(/specific1, "specific1")
    **/
    public function specific1()
    {
    $this->addItem(array $specificParams);
    }

    public function addItem(array $specific1Params, string $specific1Function)
    {
    common();
    $this->{$specific1Function}(specific1Params);
    }

    } // MyController

  • 2019-09-06 Diego Aguiar

    Hey Avraham Markov

    I don't think that it's a good idea to use hierarchies like that on controllers. If you want to re-use some methods among controllers, then, you can create a base class to hold all that logic, or maybe use a treat, besides that, what a controller should only have are route actions

    Cheers!

  • 2019-09-06 Avraham Markov

    Hello!
    I have controller and 2 child classes,
    pretty similar to Template design pattern.

    public class MyController
    {
    /**
    *
    *@Route("/add-item", name="addItem")
    */
    public function addItem(){
    $this->common();
    $this->specific();
    }

    public function common() { ...}
    }

    } //MyController

    public class Child1 extends MyController
    {
    public function specific( ) {...};
    } // Child1

    public class Child2
    {
    public function specific() {...}
    } // Child2

    I want to build links from twig so child class Child1::addItem be called.
    Is there some special annotation for that?
    How can it be achieved?

    Thanks!

  • 2019-08-12 Diego Aguiar

    Hey T. Wagner

    I'm sorry for the late reply. For some reason our software lost track of messages for a couple of days but it's back on business again!

    As Vladimir said in the other comment. It seems like a problem with your web server. Probably this guide may help you out configuring it right https://symfony.com/doc/cur...
    But, I recommend using Symfony's built-in webserver, it's just easier and faster to use when working locally

    Cheers!

  • 2019-08-12 Vladimir Sadicov

    Hey T. Wagner

    Looks like you webserver doesn't pass you request to public/index.php. First page works because server pass / to index.php by default. If you are using apache behind the MAMP, than you should try to install symfony/apache-pack and it should fix it.

    Cheers!

  • 2019-08-08 T. Wagner

    Not sure where my last comment went - or how to get the "support" that is advertised in the subscription promotional...

    In this video, things seems to work as advertised.. until we get to the second method


    /**
    * @Route("/")
    */
    public function homepage()
    {
    return new Response("OMG my first page");
    }

    /**
    * @Route("/news/item")
    */
    public function show()
    {
    return new Response("Content for the second page");
    }

    I'm using MAMP to serve up these pages.. I've got a virtual host pointing at http://spacebar
    So

    http://spacebar/
    Works
    http://spacebar/news/item
    Does not work (e.g., throws a 404 page not found

    The full controller page looks like this


    ponent\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;

    class ArticleController
    {

    /**
    * @Route("/")
    */
    public function homepage()
    {
    return new Response("OMG my first page");
    }

    /**
    * @Route("/news/item")
    */
    public function show()
    {
    return new Response("Content for the second page");
    }

    }

  • 2019-08-08 T. Wagner

    First annotated thing worked...
    Second... getting page not found...
    (I shorted the URL to /news for brevity)

    /**
    * @Route("/news")
    */
    public function show() {
    return new Response('future page');
    }

  • 2019-08-01 Diego Aguiar

    Hey Saul Solé

    Thanks for sharing it :)
    If you want to know more about configuring Apache for a Symfony app you can read this guide: https://symfony.com/doc/cur...
    You may have to add the DirectoryIndex index.php rule if your homepage never ends loading

    Cheers!

  • 2019-08-01 Saul Solé

    If anybody is having a 404 error from apache here's what i did to solve it:
    composer require symfony/apache-pack.
    manually create your .htaccess file and fill it with this:
    https://github.com/symfony/...

    And it should work just fine.

  • 2019-05-06 Victor Bocharsky

    Hey Sourodipta,

    I'd recommend you to take a look at docs about this: https://symfony.com/doc/cur... . In particular:
    > like match regular expressions
    https://symfony.com/doc/cur...

    > HTTP methods
    https://symfony.com/doc/cur...

    > host names
    https://symfony.com/doc/cur...

    We do cover some of it in further screencasts, but I'd not recommend you to jump to them directly and skip chapters to avoid losing context. Just go further in this track: https://symfonycasts.com/tr... . Otherwise, you can use our search for find related articles.

    I hope this helps!

    Cheers!

  • 2019-05-02 Sourodipta Guha

    How to validate url in the route. Can you please help me in that regards And can provide me the tutorial link on

    Sure, you can do fancier things with routes, like match regular expressions, HTTP methods or host names - but that will all be pretty easy for you now.

    Thanks

  • 2019-04-25 weaverryan

    Hmm, I don't! I just checked it out. It looks crazy! Really beautiful! I imagine it takes some getting used to!

  • 2019-04-23 AbelardoLG

    Do you know the Firacode font?

  • 2019-04-23 weaverryan

    Hey AbelardoLG!

    It's Menlo - size 19 px :).

    Cheers!

  • 2019-04-23 AbelardoLG

    Thanks, but I referred to the font used to code your examples in PHPStorm.

  • 2019-04-23 Leanna Pelham

    Hi AbelardoLG the little notes that roll up in our videos use the Open Sans font

  • 2019-04-19 AbelardoLG

    Those which are integrated into your explanations.

  • 2019-04-18 Victor Bocharsky

    Hey AbelardoLG ,

    What screenshots do you mean?

    Cheers!

  • 2019-04-17 AbelardoLG

    Hi there,
    What's the font which is used in screenshots?

    Best regards.

  • 2019-04-11 Diego Aguiar

    Really? PHPStorm? that's even weirder! haha, but I'm glad to hear that your problem is fixed now

    Cheers!

  • 2019-04-10 Teodora Moldovan

    Thank you! I tried clearing the cache before and it didn’t work. However, it worked after I closed and reopened PhpStorm.

  • 2019-04-10 Diego Aguiar

    Hey Teodora Moldovan

    That's odd, it makes me think that you may have restricted that route to work with only specific request methods (such as POST). Let me see the output of your php bin/console debug:router
    BTW, try clearing the cache, I mean, just in case :)

    Cheers!

  • 2019-04-10 Teodora Moldovan

    I am getting "An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "workspace_show" as such route does not exist.").". When I run php bin/console debug:router, I can find the route name there. Where is than the problem coming from?

  • 2019-02-17 weaverryan

    Hey Mau España!

    If you're serious about getting auto-completion, use PHPStorm. It's that simple. You can get some really nice things from Atom (I use it as my editor for everything *except* developing), but PHPStorm is many levels better. You will get PHP autocompletion and Symfony-specific auto-completion. You can out our phpstorm tutorial to learn more about this: https://symfonycasts.com/sc...

    Cheers!

  • 2019-02-16 Mau España

    Hi!! I have a question, when I want the autocomplete for my code php don't appear, but in my first test appear, I have the package php-autocomplete, but in this test don't work, what can I do?
    PD1: Sorry for my english.
    PD2: I'm using Atom instead phpstorm

  • 2019-01-08 Victor Bocharsky

    Glad to hear it works now!

    Cheers!

  • 2019-01-08 Dmitrii Utrobin

    Thanks a lot, Victor!
    I didn't change nginx configuration to one input.
    I change nginx conf
    location / {
    try_files $uri $uri/ /index.php$is_args$args;
    }

    And it works

  • 2019-01-08 Victor Bocharsky

    Hey Dmitrii,

    First of all, try to clear the cache! Especially, if you're running your website in prod mode. Then, here's the trick to make sure if your route exist or no - debug it in console with "php bin/console debug:router" and search for "/news/why" in the output. Maybe your route has some prefix you forgot about :)

    If nothing helped, please, double sure you use the correct namespace: "Symfony\Component\Routing\Annotation\Route". But it may depend on your Symfony version. For older version you probably need to use this one: "Sensio\Bundle\FrameworkExtraBundle\Configuration\Route" - at least you can try to use this one, but not for the latest version.

    Cheers!

  • 2019-01-08 Dmitrii Utrobin

    Hello! When I use Route, i get error 404 Not Found.

    ArticleController.php

    namespace App\Controller;

    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;

    class ArticleController
    {
    /**
    * @Route("/")
    */
    public function homepage()
    {
    return new Response("My first page done! v2");
    }

    /**
    * @Route("/news/why")
    */
    public function show(){
    return new Response("Future page to show one spse");
    }
    }

    Homepage is working. But "/news/why" page not working. I get error 404.
    Help to fix it, please.

  • 2018-12-20 suleman khan

    Thanks Buddy it worked

  • 2018-12-18 Diego Aguiar

    You don't need to prefix with a "$" your Route wildcard. You forgot to type-hint your action's argument also

  • 2018-12-18 suleman khan

    its till not working, Please do have a look on code

    namespace App\Controller;

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;

    class HomeController extends AbstractController
    {
    /**
    * @Route("/")
    */
    public function index()
    {
    return new Response("<h1>Symfony PHP Framework</h1>");
    }

    /**
    * @Route("/news/{$slug}")
    */
    public function show($slug)
    {
    $comments = [
    'Laravel is PHP Framework',
    'Cake PHP is PHP Framework',
    'Symfony is PHP Framework'
    ];
    return $this->render('article/show.html.twig',[
    'title'=>'PHP Benchmark',
    'comments'=>$comments
    ]);
    // return new Response("Welcome to News Section");
    }
    }

  • 2018-12-18 Diego Aguiar

    Hey suleman khan

    You have to double check two things:
    1) Your route annotations are correct:


    /**
    * @Route("/news/{slug}")
    */
    public function someAction(Article $article) { ... } # Important to type-hint the argument with the correct Entity class

    2) You must have an article stored with it's slug field set to "ss"

    Cheers!

  • 2018-12-17 suleman khan

    my /news/why-asteroids page is working but when i am using {slug} in my route annotation its not working it says
    No route found for "GET /news/ss"

  • 2018-12-17 Victor Bocharsky

    Hey Suleman,

    So, you use a real web server line Nginx or Apache, right? Then you need to point your web server's document root to the public/ directory where the index.php is located. For example, take a look at this docs to see how configure Nginx: https://symfony.com/doc/cur... . Or see the same page for Apache configuration.

    Cheers!

  • 2018-12-15 suleman khan

    Hello sir i am using local server on my computer

    while running this url its not working
    localhost/the_spacebar/news/why-asteroids-taste-likebacon but its not working

    its working when i am calling article controller like this

    localhost/the_spacebar/public/

    Please do provide solutions

  • 2018-12-12 Victor Bocharsky

    Haha, probably so... thanks! ;)

    Cheers!

  • 2018-12-11 weaverryan

    Hey yao!

    Yep, that's totally ok :). When I recorded this tutorial, that package downloaded 6 things. But a few months ago, one of the packages was removed (nothing too important) and so now you only get 5.

    Cheers!

  • 2018-12-11 yao

    Is it normal that the debug pack just has 5 symfony plugins instead of 6 ? bc in the tutorial he said it comes with 6.

  • 2018-12-11 yao

    So that means you are senior right now... Great job

  • 2018-12-10 Victor Bocharsky

    Hey Yao,

    Hm, I personally started to get familiar with Symfony since 2.1, but mostly started developing apps since 2.3 IIRC :)

    Cheers!

  • 2018-12-10 yao

    How long do you use Symfony for developing apps ?

  • 2018-12-10 Victor Bocharsky

    Yay, glad you had got it working before even we replied you. And yeah, it was an easy fix ;)

    Cheers!

  • 2018-12-10 yao

    Hi Victor,

    Nice to read you. Yeah i finally fixed my issue by replacing "Sensio\Bundle\FrameworkExtraBundle\Configuration\Route" with "Symfony\Component\Routing\Annotation\Route" class which is really cool.

    Thanks for your assistance.

  • 2018-12-10 Victor Bocharsky

    Hey Yao,

    I see you noticed this comment: https://symfonycasts.com/sc... - great, and I suppose your problem is solved. So basically, "Symfony\Component\Routing\Annotation\Route" class is a new official way to add routes annotations instead of deprecated "Sensio\Bundle\FrameworkExtraBundle\Configuration\Route" one. But instead of providing a BC break, Symfony warn us first saying it will be removed in future releases so you have time to update your code.

    Cheers!

  • 2018-12-09 yao

    Thanks Mike it works.

  • 2018-12-09 yao

    Hi guys , I am a new beginner on this course. And i already face some issues.

    someone can help me with this please.

    After adding

    /**
    * @Route("/")
    */

    I have this path but !!!!!!!
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

    the last word Route is crossing. And it says that Class Route is depreciated

    thank you!

  • 2018-11-10 Hunter Baba

    I got the solution i have not added this - "use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    ".
    added and result came

  • 2018-11-10 Hunter Baba

    When i run composer require annotations its not installing and configuring these things and when i write annotations in controller its not working. HELP ASAP. In my composer.json file "sensio/framework-extra-bundle": "^5.2", is there

  • 2018-11-08 Advocatus Kakorozya

    Thank you so much! noted that

  • 2018-11-07 Diego Aguiar

    In yaml the identation matters. If you have a key idented one level further, then that key is related to its parent (the key above it)

    Probably this post may help you out understanding the syntax: https://www.codeproject.com...

    Cheers!

  • 2018-11-07 Advocatus Kakorozya

    I have just fixed just by re-doing the process on the router.yaml but still my eyes can't spot the difference

  • 2018-11-07 Advocatus Kakorozya

    Thank youi @DiDiego Aguiar
    Yes, I changed it according to the tutorial above as follows

    index:
    path: /

    controller: App\Controller\ArticleController::homepage

  • 2018-11-06 Diego Aguiar

    Hey Advocatus Kakorozya

    Welcome to the Symfony world!

    It means that you have a syntax error in your "config/routes.yaml" file. Did you change it? Could you show it to me?

    Cheers!

  • 2018-11-06 Advocatus Kakorozya

    Hello,
    I am new to symfony and PHPStorm
    I am running my first project using "php bin/console server:run" whereby the server is running fine
    The problem come when I create router.yaml and ArticleController as per the tutorial above, when I refresh the page I get the following error

    (7/7) Twig_Error_Runtime
    An exception has been thrown during the rendering of a template ("The file "C:\wamp64\www\my_project\config/routes.yaml" does not contain valid YAML in C:\wamp64\www\my_project\config/routes.yaml (which is loaded in resource "C:\wamp64\www\my_project\config/routes.yaml").").

    What could be the problem here?

  • 2018-10-31 Hichem Touati

    nvm the yaml routes were commented out. fixed it

  • 2018-10-31 Hichem Touati

    For some reason the page is not changing. And i have no idea what the problem could be.

  • 2018-10-29 weaverryan

    Hi Simone Martinucci!

    Welcome to Symfony! :)

    When you go to /new/prova, what does the error look like? Is it a nice, beautiful "Not found found" Symfony error? Or an ugly, white error with black text? A screenshot would be IDEAL!

    Also, can you post your code? What does your route & controller look like? Are you using the built-in php web server like we suggest (by running php bin/console server:run) or something like Apache or Nginx?

    Let us know and we'll do our best to help!

    Cheers!

  • 2018-10-29 Simone Martinucci

    Hello! I'm new beginner in symfony, i wrote this code:

    but when i go to type in the browser the url /news/prova return a 404 error ... can you help me please??

  • 2018-09-27 Diego Aguiar

    Hey @Ganda

    Looks like this file "your-app/config/routes.yaml" contains invalid YAML code. Could you double check it?

    Cheers!

  • 2018-09-27 Ganda Magassa

    I'm a beginner in symfony ,
    I try to run this command : composer require annotations
    But i have this error

    ~/app-synfony$ composer require annotations
    Using version ^5.2 for sensio/framework-extra-bundle
    ./composer.json has been updated
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Restricting packages listed in "symfony/symfony" to "4.1.*"
    Nothing to install or update
    Generating autoload files
    ocramius/package-versions: Generating version class...
    ocramius/package-versions: ...done generating version class
    Executing script cache:clear [KO]
    [KO]
    Script cache:clear returned with error code 1
    !!
    !! // Clearing the cache for the dev environment with debug
    !! // true
    !!
    !!
    !! In FileLoader.php line 168:
    !!
    !! The file "/home/gmagassa/app-synfony/config/routes.yaml" does not contain v
    !! alid YAML in /home/gmagassa/app-synfony/config/routes.yaml (which is loaded
    !! in resource "/home/gmagassa/app-synfony/config/routes.yaml").
    !!
    !!
    !! In YamlFileLoader.php line 64:
    !!
    !! The file "/home/gmagassa/app-synfony/config/routes.yaml" does not contain v
    !! alid YAML.
    !!
    !!
    !! In Parser.php line 582:
    !!
    !! Indentation problem in "/home/gmagassa/app-synfony/config/routes.yaml" at l
    !! ine 3 (near " controller: App\Controller\DefaultController::index").
    !!
    !!
    !! cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>
    !!
    !!
    Script @auto-scripts was called via post-update-cmd

  • 2018-09-17 weaverryan

    Hey there!

    Yes! This is normal :). We talk about about that symfony.lock file here - https://symfonycasts.com/sc... - but basically, it is a file that keeps track of what recipes have been installed.

    But, I think this isn't really your question - you're probably wondering "Why is this 3.3 when we're working on a Symfony 4 project?". That's a GREAT question. Here's how the recipe system works: when you install symfony/console, it looks at the recipes repository https://github.com/symfony/... for a "recipe" for symfony/console. Every library is allowed to have different recipes for different versions. For example, there could be a different recipe for symfony/console version 3.3 and a different recipe for symfony/console 4.0. But usually, this isn't the case. Check out the symfony/console recipe: https://github.com/symfony/.... There is only 1! And it's for Symfony 3.3. This means that this recipe will be used when symfony/console 3.3 or *higher* is installed. THAT is why you see this number recorded in your symfony.lock file. For contrast, there is an example of a recipe that is different for different versions: https://github.com/symfony/.... In that case, if you installed symfony/debug-bundle at version 3.3, 3.4 or 4.0, you would get the "3.3" recipe. If you installed version 4.1 or higher, you would get the 4.1 recipe.

    Phew! So, great question :).

    Cheers!

  • 2018-09-17 weaverryan

    Hey Ramsey Jiang!

    Hmm. Where (what directory) does your Symfony application live in your computer? Is it in \www? Or is it in some other directory? Wherever you downloaded Symfony, you should *absolutely* have a config/packages/routes.yaml file in that directory. The fact that you don't see that means you may be looking in the wrong place, or something is very wrong.

    Let us know!

    Cheers!

  • 2018-09-14 Studen

    It's normal???:
    # www\symfony.lock
    "symfony/console": {
    "version": "3.3",

  • 2018-09-14 Student

    Need use: composer require symfony/apache-pack
    Yes, it's gen. .htaccess file, but I didn't have this file:
    \www\config\packages\routes.yaml
    I create manual, but output error

    index:
    path: /
    controller: App\Controller\ArticleController::homepage

    Yes, I have Controller too:

  • 2018-08-23 Silvestr Hašek

    Hi Victor,

    first of all thanks for your rapid response, Just for clarification of naming www. It cames from where the app will be deployed. If it's something like api.project.ltd it will be api. I believe this structure will change in future Symfony is build (by the Composer) differently, then I'm used too (No need any future respond)

    Thanks again.

  • 2018-08-23 Victor Bocharsky

    Hey Silvestr,

    Hm, I'n not against creating a subfolder for Symfony project in Git repositories, but the folder name you have a bit mislead me. For me www/ is a folder that should be the document root of your project. But only public/ dir in the Symfony folder should be the document root. But that's just a name, and if you comfort with it - great! Just remember that only public/ directory should be publicly accessible for your web server.

    What about your question: No, you don't need to commit .idea/ folder to your repository, it's personal for every developer, and PhpStorm stores there some internal information that relates to your laptop only. For example, PhpStorm remembers what opened files you have there, and each time you open / close a new file - PhpStorms writes to this directory, so you repository will be in a dirty stage every time you do something in PhpStorm. So you're right, IDE choice is personal, other devs may use another IDE, that's why you should avoid committing this folder to the repo.

    Cheers!

  • 2018-08-23 Silvestr Hašek

    Hello,

    when I opened PHPStorm it generated hidden folder inside mine project folder. To be fair as I'm new to PHPStorm and Symfony, I'm not totally beginner in web development so I started a little bit different from the tutorial, to suit my current needs (I will probably change it in future, it's just old habit of mine :-D)

    /project (git init here)
    -- /www (where Symfony lives as from tutorial)
    -- /.idea (generated by PHPStrom)

    so the question is, should I push .idea folder to git? On Jetbrain support you can read many opinions from don't push to push some only same file. My thoughts are, as I can't guarantee that everyone on the project will work whit PHPStrom it should be better to add the whole folder in .gitignore and not to push.

    But as I pointed before I'm new to PHPStorm and I really don't know what these files are, at least yet.

    Thanks for your recommendation.

  • 2018-08-20 Victor Bocharsky

    Hey Ricard,

    Nice catch! Yes, now it's optional to have "Action" suffix for your actions. Well, it was done just for simplicity and transparency. And because "Bundle:Controller:Action" syntax is deprecated. Btw, you can still use Action suffix, but this way you'll need to explicitly specify it in route configuration when using Yaml/Xml. And you can check related thread here: https://github.com/symfony/...

    Cheers!

  • 2018-08-20 Ricard Espinàs Llovet

    In Symfony 3 all the methods from the controllers were called "somethingAction". I guess in Symfony 4 that's not necessary anymore, isn't it? Could you explain me why this change of behaviour?

  • 2018-07-31 Victor Bocharsky

    Hey Mike,

    Thanks for sharing it with others! And yeah, this one is an easy win :)

    Cheers!

  • 2018-07-31 Mike

    Want to share my experience, SF 4.1.2 Deprecation Message:
    User Deprecated: The "Sensio\Bundle\FrameworkExtraBundle\Configuration\Route" annotation is deprecated since version 5.2. Use "Symfony\Component\Routing\Annotation\Route" instead.

    The solution is pretty obvious, choose the other Route Class :)

  • 2018-07-24 mouad err

    Hello weaverryan
    Thank you for your respond, all what you said is correct, no error after calling an id that's already exist in my DB.

  • 2018-07-23 weaverryan

    Hey mouad err!

    Ah, yes! My guess is that your controller method has an argument that is type-hinted with Article - something like this:


    public function index(Article $article)

    Because the Article class is a Doctrine entity, Symfony tries to automatically query for the Article from the database, by using some information from the route. Usually, you have a route that looks like this:


    /**
    * @Route("/article/{id}")
    */
    public function index(Article $article)

    And so when you go to /article/10, Symfony tries to find the Article with id 10. The error you are receiving - if you use the code from my example - is because it cannot find any Article in the database with id 10. In this chapter, we aren't using Doctrine yet, and we don't have an Article class - so you shouldn't be getting this error.

    Basically, if you really DO want to query for an Article object, this error is fine: it just means it can't find that Article object in the database. If you are NOT trying to query for an Article (maybe you copy and pasted some code), just remove that argument.

    Cheers!

  • 2018-07-23 mouad err

    I have this issue and i don't know how to solve it.
    App\Entity\Article object not found by the @ParamConverter annotation.

  • 2018-06-26 Diego Aguiar

    Awesome! I hope you are enjoying your time at KnpUniversity :)

  • 2018-06-26 Luma Macagnan

    Yep, I made a search and found it before! That's nice, I'm pretty sure I'll check it out. Kind regards.

  • 2018-06-25 Diego Aguiar

    Hey Luma Macagnan

    Thanks for the compliment!

    We are focused on PHP & Symfony, but we do have some courses about Javascript, how to create a REST API, ReactJS, Gulp, Ansible, and more. You can check our entire list of courses here: https://knpuniversity.com/c...

    If you have any other doubt or concern, don't hesitate to contact us.

    Saúde!

  • 2018-06-25 Luma Macagnan

    Amazing tutorial, thank you! You guys make it really fun and easy to understand.

  • 2018-03-22 Tess Hsu

    God, thank Victor, yes, it is work after correct the controller name, sorry again

  • 2018-03-22 Victor Bocharsky

    Hey Tess,

    A simple mistake: your controller's name is "MenuControllerController" but should be just "MenuController" ;)

    Cheers!

  • 2018-03-21 Tess Hsu

    Hi,
    I wonder if someone had try to add another controller to play with,

    My steps is followed:
    1 add A new controller called MenuController.php under src/Controller/


    namespace App\Controller;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

    class MenuControllerController extends AbstractController
    {
    /**
    * @Route("/about", name="app_aboutpage")
    */
    public function aboutpage()
    {
    return $this->render('article/aboutpage.html.twig');
    }
    }

    2 Add template in article/aboutpage.html.twig


    {% extends 'base.html.twig' %}

    {% block body %}
    <div class="container">
    <div class="row">

    <div class="row">
    test create about page
    </div>
    </div>
    </div>
    {% endblock %}

    3 modify this path in base.html.twig


    <li class="nav-item">
    <a style="color: #fff;" class="nav-link" href="{{ path('app_aboutpage') }}">About</a>
    </li>


    Then run server and it is show error message:

    FileLoaderLoadException
    The autoloader expected class "App\Controller\MenuController" to be defined in file "/Users/webdev/Documents/dossier_web/symfony/the_spacebar/vendor/composer/../../src/Controller/MenuController.php". The file was found but the class was not in it, the class name or namespace probably has a typo in /Users/webdev/Documents/dossier_web/symfony/the_spacebar/config/services.yaml (which is loaded in resource "/Users/webdev/Documents/dossier_web/symfony/the_spacebar/config/services.yaml").

    It is possible to know where did i doing wrong since I just want to do: add a Controller-> make about link to go to http://127.0.0.1:8000/about

    thank you so much advanced

  • 2018-03-13 Agung

    Hey, i also have the same error, for the route "/" is no problem, for route "/news/..." give error message, after i check there is some kind a silly mistake that i have done. After you install annotations composer will generate annotations.yaml in routes folder, and i accidentally comment it (the one you should comment is routes.yaml). I hope this will help.

  • 2018-02-09 Diego Aguiar

    Hey Mohammad

    On Symfony4 you have to install "apache-pack" https://packagist.org/packa...
    it will generate a ".htaccess" file at your public directory, so you have to configure your apache to allow overrides

    Cheers!

  • 2018-02-09 Mohammad

    I am having the same issue. I am using Vagrant and running apache on it, I have Symfony3 project and I have the symfony4 on the same server. Symfony3 has no issue while Symfony4 is not working well.

    The error is from the server, the server throw 404 on all internal pages.I know this issue happen when your apache is not configured right and you forgot the to configure the Directory.., but it is different here bcz I have the apache conf correct.

    What is making me more crazy is that I am using PHPUnit testing and the test is able to reach the internal page url but when I use the browser it throw 404, also ajax calls throw 404.

  • 2018-02-08 Ramsey Jiang

    It can find it. I fix it though I don't know why it is suddenly fixed.

  • 2018-02-08 Diego Aguiar

    Oh boy, you ain't gonna believe it, just move up your method "news" right before "showAction". The problem is that Symfony returns the first route that matches the request, and since your route "@Route("/{id}"..." is defined first and has a wildcard, then your other route "@Route("/news/{slug}")" will never be found.

    I hope it makes sense to you :)
    Cheers!

  • 2018-02-08 Ramsey Jiang

    Hey Diego,

    I can hit other routes.

    For example, the following codes I can access them.
    /**
    * @Route("/")
    */
    public function indexAction()
    {
    return new Response('OMG! My first page already! Wooooo!');
    }

    /**
    * @Route("/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1})
    */
    public function showAction($id)
    {
    return new Response('The number is '. $id);
    }

    But I cannot access the next one.

    /**
    * @Route("/news/{slug}")
    */
    public function news($slug)
    {
    return new Response(sprintf('Today new is "%s"', $slug));
    }

    I've already generated .htaccess, but it still not work. Whether I need to modify .htaccess a little bit?

  • 2018-02-08 Diego Aguiar

    Hey Ramsey Jiang

    Can you hit any other route? Let me see your routing configuration.
    One more thing, maybe your ".htaccess" file is not being read by Apache, you need to add this directive into your VirtualHost config "AllowOverride All"

    Cheers!

  • 2018-02-08 Ramsey Jiang

    Hey @weaverryan

    I did that before. Yes, it generate .htaccess automatically, but http://127.0.0.1:8000/index.php/news/test still not work. Should I change somthing in .htaccess file?