2

Is there a way to get the composer autoloader instance inside a Symfony2 Controller?

4
  • why would you want that? Commented Dec 2, 2013 at 21:48
  • You don't need it - unless you provide an explanation why you do in your question. :) Commented Dec 2, 2013 at 22:01
  • See this question (it's the reason why I need it): stackoverflow.com/questions/20324414/… Commented Dec 2, 2013 at 22:50
  • Also this question requires this ability when the path is dynamic and not known until after the controller finds what template the user is using. Commented Jan 1, 2015 at 0:21

2 Answers 2

3

Yes - there is a way.

And assuming that you want to know how to actually get the loader then you can do this in your controller:

class MyController
    function myAction()
    {
        die(get_class($GLOBALS['loader'])); // Composer\Autoload\ClassLoader

Should you do this? Probably not. In most cases you can tweak the loader in the app/autoload.php file.

Sign up to request clarification or add additional context in comments.

3 Comments

@Cerad Can you elaborate what problems may exist with this method? In my case I don't know which template the site is using until after my controller finds this information, so I cannot do it in the app/autoload.php.
In general, anytime you need to use a global should result a red flag.
@Cerad I agree. So how can you access the loader in Symfony the "correct" way? Can you make it a global service somehow and inject it? If you need to add paths dynamically, how else are you "supposed" to do this, according to the Symfony best practices?
1

Using the $GLOBALS did not work for me, but you can also get it like this:

$autoload_functions = spl_autoload_functions();
$loader = $autoload_functions[0][0];

this assumes that "autoload.php" has been required, AND that it is configured to prepend the composer classloader to other classloaders (the default).

NOTE: I am not saying this is good style.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.