Since we have this new movie form, we're going to want to save the data to the database. To do this let's create a Movie entity. I'm not going to generate it, let's just do this by creating a good ole fashioned PHP Class called Movie. But when I do this, notice the namespace box is empty. I could type AppBundle\Entity here, but I'm trying to do as little work as possible people!

Let's make the robots do this for you. Go into preferences, search for 'directories' and here you can see the three directories that we excluded earlier. Click on src and click the blue sources button above. Now we can see this on the right and clicking the little 'p' allows us to edit the properties. So, if we were using PSR-4 inside of this directory we could actually put our namespace prefix in this box - like KnpU. But all we needed to do was mark it as a source route, so we're done!

When we head back, oh look the Entity directory disappeared! Where did we misplace that to? Well, sometimes PHPStorm does that to empty directories. Temporarily I'll switch back to project view and now create a new PHP Class. Because of the sources change, it guesses the namespace part perfect. Call the class Movie:

9 lines src/AppBundle/Entity/Movie.php
<?php
namespace AppBundle\Entity;
class Movie
{
}

Okay switch back to Project Files and there it is. Excellent! In a second we'll set this up with some annotations, but right now I want to use it inside of my MovieController. We'll add a form here soon, and when we do, we'll need a new Movie object. So we'll say $movie = new... and I could end this with AppBundle\Entity\Movie -- but you really don't want to do that. Always go directly to the last part: in our case Movie, and let that autocomplete:

23 lines src/AppBundle/Controller/MovieController.php
... lines 1 - 4
use AppBundle\Entity\Movie;
... lines 6 - 8
class MovieController extends Controller
{
... lines 11 - 13
public function newAction()
{
$movie = new Movie();
... lines 17 - 20
}
}

Because, when you do that, it adds the use statement on line 5 which is HUGE. If you are not using the autocomplete functionality for use statements, then you're doing it wrong.

Now, if something went wrong and you didn't autocomplete or you end up with Movie here but no use statement, you can import it if you want. Just hit alt + enter. Alt enter is one of the most important shortcut we are going to see. It's called the "actions" shortcut. Often when you're inside some code. you can alt + enter and get a list of actions to do. I'll select 'import class' from this list and it will add that use statement for us.

To take this a bit further let's add a public function listAction() that will list those movies from the database. I don't want to build this out now, I just want it to return a simple Response that says "todo". So let's add return new Response and select the Response we want, which is the one from HttpFoundation. Hit tab and the use statement politely puts itself on top of our file. Finish with 'TODO'. Now let's add a route above this, @Route("/movies", name="movies_list"):

32 lines src/AppBundle/Controller/MovieController.php
... lines 1 - 7
use Symfony\Component\HttpFoundation\Response;
... line 9
class MovieController extends Controller
{
... lines 12 - 23
/**
* @Route("/movies", name="movies_list")
*/
public function listAction()
{
return new Response('TODO!');
}
}

Oh and now that we have this second endpoint, back in new.html.twig, if we want to create a link to this page, we can. And we can use another live template. Type a, hit tab, and use {{ path() }} and - amazingly - we even get auto-complete on the route name. For the link text, say "back to list':

16 lines app/Resources/views/movie/new.html.twig
... lines 1 - 5
<a href="{{ path('movies_list') }}">Back to list</a>
... lines 7 - 16

Refresh that, and there's our link right back to our list. Awesome!

So, don't. write. use statements. ever.

Leave a comment!

  • 2016-07-01 Victor Bocharsky

    Hey, thank you!

  • 2016-07-01 BIBIN JOHN

    The best php namespace tutorial.... Great... keep it up...

  • 2016-05-09 Janak

    excellent explanation. Thanks!!!

  • 2016-03-21 Emmanuel Higgins

    Wish documentation was like this.

  • 2016-01-28 TuConciencia

    120 seconds + this explanation and I'm ready to go =)
    Thank you!

  • 2016-01-16 Arturas Lapiskas

    guess i'm not the first, who say that this titorial is great! Thank you!

  • 2015-07-21 weaverryan

    Ha, 120 seconds is definitely a rush! You can't slow down the video yet, but we're adding speed control really soon :)

  • 2015-07-21 Zoe Abe

    Quite helpful, many thanks! I realized it before I know I realized it (does that make sense? :P)
    But do you happen to have a 0.75x speed playback option? 120 seconds sound like a rush to me~~ :-D

  • 2015-03-27 sancoLgates

    great explanation, thanks :)
    i get it now!

  • 2015-03-20 Braxton Overby

    I got myself ready to sit down and read/watch for several minutes on how to properly use namespaces in PHP. I appreciate how easy this tutorial was to follow.

  • 2015-01-24 Sajeepan Yogenthiran

    useful tip :-) Thank you.

  • 2014-12-10 Alberto Maturano

    Yes, It would help :D

  • 2014-12-03 Jimmy James Atauje Hidalgo

    Very nice tutorial

  • 2014-11-13 weaverryan

    Hey R0bertinski!

    I wonder if (English) sub-titles would help? I want to do the most useful thing for our non-native English-speaking friends :).

    Thanks!

  • 2014-11-12 R0bertinski

    I am used to listen videos in english, but is very complicate to understand this videos, because she speak very fast.

  • 2014-10-27 weaverryan

    So nice, thanks Troy :)

  • 2014-10-25 Troy Close

    Brilliant. I just wasted my time reading two different tutorials on namespaces and still didn't understand it. Watched your video and got it immediately. Thanks Leanna and Ryan for uncomplicating this subject.

  • 2014-07-29 Century Media

    Great overview. Only thing I think it could use is to mention that the main use of namespaces is to stop method names conflicting. Aside from that great job!

  • 2014-06-04 weaverryan

    Hi there!

    Actually, namespaces and autoloading are 2 separate things, though in practice, due to PSR-0 autoloaders, they are quite related.

    Namespaces are all about basically making class names really long, and then giving us a "use" statement to help shorten things. On its own, it doesn't help with removing the require/include statements. So you're right, on their own, namespaces actually *add* code and make things longer. Really, namespaces weren't created for you and I, they were created for library authors to avoid name collisions (like you mentioned). For us, they just make things longer :).

    But in practice (and you're totally right about this part), if you use namespaces properly, AND you use a PSR-0/PSR-4 autoloader (like the one provided in Composer), then you'll be able to remove your require/include statements. The autoloader basically leverages namespaces to do this, but namespaces on their own don't allow you to remove those ugly require/include things from your code.

    I hope that clarifies - it's confusing because namespaces *seem* to make include/require statements no longer necessary (because in practice, this is true). But in reality, on their own, they just make class names longer and mean more typing.

    Cheers!

  • 2014-06-04 ENetArch

    So, why wasn't the required_once function removed from your example? If that function is required to import your classes, then there is no purpose in updating code to include namespaces, since there is no benefit in reducing code, instead, you've increase code.

    The purpose of adding a namespace, not only has to reduce class name clashes, but also automate the finding and binding of classes somehow, otherwise there is no use to using namespaces.

  • 2014-02-12 Jerome Covington

    That was awesome. Thanks for this. Namespaces and object-oriented code in PHP are bringing me back.

  • 2014-01-23 weaverryan

    Hi there!

    Namespaces and using the include/require statements don't do the same thing - it's one of the trickiest parts of learning namespaces. You still need to include/require any file before using the class inside of it (unless you use an autoloader, like the one Composer gives you). Namespaces have nothing to do with that part.

    The point of namespaces is, basically, to give you a systematic way to make your class names longer. When you have the `Acme\Tools` namespace, the full class name ends up being `Acme\Tools\Foo`. Why is this useful? Well, on its own, it's not :). It's really so that 2 3rd-party library authors an choose 2 different namespaces so that their class names don't conflict. Namespaces really help to serve that purpose: to avoid conflicts between libraries.

    If you want to see a little bit more on the autoloading side of things (i.e. removing the need for require/include) - check out http://knpuniversity.com/scree.... Again, it's actually unrelated to namespaces.

    Cheers!

  • 2014-01-23 spudgun

    You explained what namespaces do, but you didn't explain why I might need them. You say "This is just like referring to a file by its absolute path.", so ... why don't you just do that?

    include('Acme/Tools/Foo.php');

  • 2013-12-08 JC

    Wow... you really did it in 120 secs :-)