1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Injecting a modified autoloader

Discussion in 'XenForo Development Discussions' started by Robbo, Apr 3, 2012.

  1. Robbo

    Robbo Well-Known Member

    I have been using a custom autoloader for certain tasks a hacky way and only just noticed the setInstance method which I should have been using all along. But then I don't know how...

    getInstance is final and uses new self(); This means whenever calling it it is always giving an instance of XenForo_Autoloader due to supporting PHP 5.2 (could be resolved with 5.3 by simply doing new static();). So then I thought okay I'll just make my instance the old fashioned way, but again no because the constructor is protected (as it should be I guess). So the setInstance method simply doesn't work because you can't create a new instance. Unless I am missing something? I can hack it and do a getNewInstance() and then inject that but that shouldn't be needed?
     
  2. Robbo

    Robbo Well-Known Member

    I am assuming the getInstance isn't meant to be final and the $_instance isn't meant to be private? That would solve this as you could simply re-declare getInstance.

    Anyways, here is my autoloader incase someone needs something similar. Simply adds autoloading for namespaces.

    Code:
    <?php
    
    class Watermark_Autoloader extends XenForo_Autoloader
    {
    	protected static $_setupExtension = false;
    
    	protected function _setupAutoloader()
    	{
    		spl_autoload_register(array($this, 'autoload'));
    	}
    
    	public function autoloaderClassToFile($class)
    	{
    		if (file_exists($filePath = parent::autoloaderClassToFile($class)))
    			return $filePath;
    
    		if (preg_match('#[^a-zA-Z0-9_\\\]#', $class))
    		{
    			return false;
    		}
    
    		return $this->_rootDir . '/' . str_replace('\\', '/', $class) . '.php';
    	}
    
    	public static function setupAutoloaderExtension()
    	{
    		if (!self::$_setupExtension)
    		{
    			$instance = new self();
    			self::setInstance($instance);
    			$instance->setupAutoloader(XenForo_Application::getInstance()->getRootDir() . '/library');
    		}
    	}
    }
     

Share This Page