I am getting started with Symfony 2 & I am following this tutorial. Now, this tutorial is easy & I was able to follow it completely. This is the code in my Controller
<?php
namespace DemoCompany\HelloBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
class HelloController{
public function indexAction($name){
return new Response('<h1>hello ' . ucfirst($name) . '</h1>');
}
}
Now, I have some questions
-
When I run the code without including
namespace DemoCompany\HelloBundle\Controller;, it gives me an error. But it does work fine when this line is included; so I want to know: Why does it work with namespace statement & why doesn’t it work without namespace. Please clarify. -
Follow up question: I am returning a new
Responseobject but it is neither being defined, nor is my classHelloControllerextending some baseclass (which may have this response object defined). So the question is: How is PHP able to find & then load this file? -
In Symfony, do custom controllers/models/views need to extend some base class? For example, in Codeigniter, we have to do something like
class Blog extends CI_Controller, so that all the methods defined in CI_Controller would be available in current scope using$this. Does Symfony have the same practice or does it do something different? -
Since this controller is namespaced to
DemoCompany\HelloBundle\Controller, how come normal PHP functions work without a backslash?
I’ve only very briefly used Symfony2, here are my answers though:
1) That’ll be because Symfony needs your Controller to exist in the
DemoCompany\HelloBundle\Controllernamespace for autoloading2) At
use Symfony\Component\HttpFoundation\Response;, you’re telling PHP to look in there if the method can’t be found locally3) Don’t know on that one…
4) Built-in PHP functions aren’t in any specific namespace (namespaces are new to PHP), so work anywhere