Is there a way to get the composer autoloader instance inside a Symfony2 Controller?
-
why would you want that?Markus Kottländer– Markus Kottländer2013-12-02 21:48:39 +00:00Commented Dec 2, 2013 at 21:48
-
You don't need it - unless you provide an explanation why you do in your question. :)Sven– Sven2013-12-02 22:01:16 +00:00Commented Dec 2, 2013 at 22:01
-
See this question (it's the reason why I need it): stackoverflow.com/questions/20324414/…Steffen Brem– Steffen Brem2013-12-02 22:50:06 +00:00Commented 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.Chadwick Meyer– Chadwick Meyer2015-01-01 00:21:30 +00:00Commented Jan 1, 2015 at 0:21
Add a comment
|
2 Answers
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.
3 Comments
Chadwick Meyer
@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.Cerad
In general, anytime you need to use a global should result a red flag.
Chadwick Meyer
@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?
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.