Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces in vendor files (CakePHP2.x and PHP5.4.3)

I want to use a css parser that uses namespaces. I put the files in vendors and app imported it. but the script itself does not seem to find its classes

At the top of my class I import the file:

App::import('Vendor', 'Sabberworm', array('file' => 'Sabberworm/CSS/Parser.php'));

which is in /root/vendors/Sabberworm/CSS/ (all files are in this namespace)

Inside my class method I create a new instance:

public function parse($content) {
    $oParser = new Sabberworm\CSS\Parser($content);
    ...
}

So far so good. But if I now want to call $oCss = $oParser->parse(); it fatal errors:

"Fatal error: Class 'Sabberworm\CSS\CSSList\Document'"

it fails then because it requires the other files (which should be loaded using namespaces). the root vendors folder is in the include path and the foreign script seems to set the namespace to "namespace Sabberworm\CSS;". what am I missing? I am kinda new to namespaces.

like image 512
mark Avatar asked Jan 16 '23 21:01

mark


1 Answers

Add this to bootstrap

spl_autoload_register(function($class) {
    foreach(App::path('Vendor') as $base) {
        $path = $base . str_replace('\\', DS, $class) . '.php';
        if (file_exists($path)) {
            return include $path;
        }
    }
});

Or just this inside the function:

$path = APP . 'Vendor' . DS . str_replace('\\', DS, $class) . '.php';
if (file_exists($path)) {
    include $path;
}
like image 89
tigrang Avatar answered Jan 29 '23 12:01

tigrang