Loading namespaced classes with Symfony 1.4's autoloader?

后端 未结 3 1488
独厮守ぢ
独厮守ぢ 2021-02-03 13:07

How to register namespaces (with PHP 5.3) in the Symfony 1.4 for the autoloader class feature (like the Symfony 2.0)?

相关标签:
3条回答
  • 2021-02-03 13:44

    You can use Autoloader from Symfony2 in Symfony 1.4 framework.

    1. Copy Symfony2 classloaders to vendor directory of your Symfony 1.4 sandbox project:

    SF_ROOT_DIR/lib/vendor/Symfony2/src/Symfony/Component/ClassLoader/UniversalClassLoader.php

    SF_ROOT_DIR/lib/vendor/Symfony2/src/Symfony/Component/ClassLoader/ApcUniversalClassLoader.php

    2. Modify your SF_ROOT_DIR/config/ProjectConfiguration.class.php file as follows:

    require_once dirname(__FILE__) . '/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
    require_once dirname(__FILE__) . '/../lib/autoload/sfClassLoader.class.php';
    sfCoreAutoload::register();
    
    class ProjectConfiguration extends sfProjectConfiguration {
    
        public function setup() {
            $this->namespacesClassLoader();
            $this->enablePlugins('sfDoctrinePlugin');
        }
    
        public function namespacesClassLoader() {
           if (extension_loaded('apc')) {
               $loader = new ApcUniversalClassLoader('S2A');
           } else {
               $loader = new UniversalClassLoader();
           }
           $loader->registerNamespaces(array(
              'Pohon' => __DIR__ . '/../lib/vendor/Pohon/src'));
           $loader->register();
        }
    
    }
    

    3. Register desired namespaces:
    eg. I want to load class:

    Pohon\Tools\String\Utils\Slugify.

    Filename must be:

    SF_ROOT_DIR/lib/vendor/Pohon/src/Pohon/Tools/String/Utils/Slugify.php

    and registered namespace as follows:

    Pohon => SF_ROOT_DIR/lib/vendor/Pohon/src

    0 讨论(0)
  • 2021-02-03 13:50

    You can use Composer and it's very easy. Just install it on your machine (you probably have already since it's 2015 now) and run in your project folder:

    composer init 
    

    You can then install all the packages you want with composer and include just this line in your ProjectConfiguration.class.php:

    require_once __DIR__.'/../vendor/autoload.php';
    

    Note that paths may differ if you changed the default Symfony1.4 directory structure.

    0 讨论(0)
  • 2021-02-03 14:09

    Symfony uses the spl_autoload_register() function to register its own autoloader (sfAutoload).

    You can register your own handler in the initialize() function of your Project/Application/Plugin. (whichever applies).

    This is, for example, also what the Swift_Mailer plugin does: it registers its own autoloader when needed.

    0 讨论(0)
提交回复
热议问题