Autoloading a class in Symfony 2.1

拜拜、爱过 提交于 2019-11-28 13:32:40

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.

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 ;-)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!