0
votes

I have an controller:

<?php
namespace Acme\HelloBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
//use Symfony\Component\HttpFoundation\Response;
class HelloController extends Controller
{
    public function indexAction($name)
    {
        return new Response('<html><body>Hello '.$name.'!</body></html>');
    }
}

When I run the driver returns the error

1/1 ClassNotFoundException: Attempted to load class "Response" from namespace "Acme\HelloBundle\Controller" in D:\symfony2\src\Acme\HelloBundle\Controller\HelloController.php line 14. Do you need to "use" it from another namespace? Perhaps you need to add a use statement for one of the following: Symfony\Component\BrowserKit\Response, Symfony\Component\HttpFoundation\Response, Doctrine\CouchDB\HTTP\Response.

As I can load the "use Symfony\Component\HttpFoundation\Response;" class for all my controllers without the need to be including it in each controller

Help please, nedd autoload of HttpFoundation\Response

Thanks

2
You need the use statement. Just the way php namespaces work. Unless you want to do return new Symfony\Component\HttpFoundation\Response() but that is not ideal.Cerad

2 Answers

2
votes

When you use the use statement you are not including the file that contains the class, you are aliasing/importing the namespace.

You import the namespace like so:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

Or you could alias a class, for example the Response class could be aliased to SymfonyResponse:

use Symfony\Component\HttpFoundation\Response as SymfonyResponse;

Then you can use the new alias in your code:

return new SymfonyResponse('<html><body>Hello '.$name.'!</body></html>');

If you don't import the class namespace the autoloader will think that you are trying to load a Response class within the current namespace: Acme\HelloBundle\Controller which doesn't exist.

Now, if you don't want to add the use statement at the top of the file, use the fully qualified name:

return new \Symfony\Component\HttpFoundation\Response('<html><body>Hello '.$name.'!</body></html>');

I personally would recommend against this as it can get crazy depending on who many classes you are using ... just add the use statement. Some IDEs will add it automatically for you (e.g. PHPStorm).

For more information see

  1. Using namespaces: Aliasing/Importing
  2. How to use namespaces, part 1: the basics
  3. How to Use PHP Namespaces, Part 2: Importing, Aliases, and Name Resolution
  4. Composer namespaces in 5 minutes
0
votes

Do what the error message says. Uncomment the use statement that imports the Request class into the current namespace and let the autoloader to its work.

A use statement does not trigger autoload, the file is only included if the class is referenced in executed code.