Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoloading a class in Symfony 2.1

Tags:

symfony-2.1

I'm porting a Symfony 1.2 project to Symfony 2.x. I'm currently running the latest 2.1.0-dev release.

From my old project I have a class called Tools which has some simple functions for things like munging arrays into strings and generating slugs from strings. I'd like to use this class in my new project but I'm unclear how to use this class outside of a bundle.

I've looked at various answers here which recommend changing app/autoload.php but my autoload.php looks different to the ones in the answers, maybe something has changed here between 2.0 and 2.1.

I'd like to keep my class in my src or app directories as they're under source control. My vendors directory isn't as I'm using composer to take care of that.

Any advice would be appreciated here.

like image 612
Al Bennett Avatar asked Aug 20 '12 21:08

Al Bennett


2 Answers

Another way is to use the /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. Works quite well for me, so far.

You're correct, I stumbled upon the changes in autoload from 2.0 to 2.1. The above code works fine with the latest version, to which I upgraded my project ;-)

like image 85
maschmann Avatar answered Nov 09 '22 12:11

maschmann


For a simple case like this the quickest solution is creating a folder (for example Common) directly under src and put your class in it.

src
  -- Common
    -- Tools.php

Tools.php contains your class with proper namespace, for example

<?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 proper folder structure and namespace as above, it will work without touching app/autoload.php.

like image 25
mgiagnoni Avatar answered Nov 09 '22 12:11

mgiagnoni