Reputation: 1927
I didn't find similar question so here it goes. Is it possible (if yes, then how) to autoload classes from outside the project? I.e:
There is this directory structure:
commons/
bundle1/
app1/
...
composer.json
...
app2/
inside composer.json file I would like to do the following:
"autoload": {
"psr-0": {
"CommonNamespace\\": "../commons/bundle1/"
}
},
But it did not work. So I tried to use autoload.php file that resides inside app1/ directory:
$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('CommonNamespace\\', '../../commons/bundle1');
$loader->register();
But it is ignored aswell.
Are there other ways of doing it? Or how do you share your code between applications and make sure it is up to date all the time?
Upvotes: 2
Views: 669
Reputation: 48865
Your first example is the way to go. Just a question of getting the syntax correct.
Here is some working code:
$loader = require __DIR__.'/../vendor/autoload.php';
$loader->add('Cerad', __DIR__ . '/../../cerad2/src');
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
return $loader;
No need to call $loader->register();
No need for backslashes after the namespace.
As far as your second question about using external code, it's fairly easy to make your own composer packages and then just use composer to include it in your application.
https://getcomposer.org/doc/02-libraries.md
Example of including a github based composer package using composer.json
"repositories": [
{
"type": "vcs",
"url": "https://github.com/cerad/FOSUserBundle"
}
],
"require": {
# Grabs my cloned version of FOSUserBundle from github
"friendsofsymfony/user-bundle": "dev-master"
Upvotes: 2
Reputation: 1927
I ended up writing short autoloader(code below) which I put inside app/autoload.php file, right before return $loader line. It works perfect. Just messes up deployment.
spl_autoload_register(function ($class) {
$prefix = 'Somenamespace\\';
$base_dir = __DIR__ . '/../../commons/';
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) { return; }
$relative_class = substr($class, $len);
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
if(file_exists($file)) {
require $file;
}
});
Upvotes: 0