Class autoload in Symfony 2.1

I am migrating the Symfony 1.2 project to Symfony 2.x. I am currently running the latest version 2.1.0-dev.

From my old project, I have a class called "Tools" that has some simple functions for things like arrays of iterating over strings and creating a bullet from strings. I would like to use this class in my new project, but I do not understand how to use this class outside the package.

I reviewed various answers here that recommend changing the /autoload.php application, but my autoload.php looks different in the answers, maybe something has changed here between 2.0 and 2.1.

I would like to keep my class in the src or app directories as they are under source control. My suppliers catalog is not the way I use the composer to take care of this.

Any advice would be appreciated here.

+8
source share
2 answers

For a simple case like this, the fastest solution creates a folder (like Common ) directly under src and puts its class in it.

 src -- Common -- Tools.php 

Tools.php contains your class with the correct namespace, e.g.

 <?php namespace Common; class Tools { public static function slugify($string) { // ... } } 

Before calling your function, do not forget the use statement

 use Common\Tools; // ... Tools::slugify('my test string'); 

If you put your code under src following the correct folder structure and namespace as mentioned above, it will work without touching app/autoload.php .

+7
source share

Another way is to use /app/config/autoload.php:

 <?php use Doctrine\Common\Annotations\AnnotationRegistry; $loader = require __DIR__.'/../vendor/autoload.php'; $loader->add( 'YOURNAMESPACE', __DIR__.'/../vendor/YOURVENDOR/src' ); // intl if (!function_exists('intl_get_error_code')) { require_once _DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php'; $loader->add('', __DIR__.'/../vendor/symfony/symfony/src/Symfony/Component/Locale/Resources/stubs'); } AnnotationRegistry::registerLoader(array($loader, 'loadClass')); return $loader; 

Just replace YOURNAMESPACE and YOURVENDOR with your values. Still works well for me.

You are right, I came across changes in autoload from 2.0 to 2.1. The above code works fine with the latest version that I updated my project on; -)

+12
source share

All Articles