4

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
mark
  • 21,691
  • 3
  • 49
  • 71

1 Answers1

9

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;
}
tigrang
  • 6,767
  • 1
  • 20
  • 22
  • I like the first one. It worked right away (I put it into the lib class which uses the vendor stuff). thanks a lot! now i can continue working on the AssetSprite stuff. – mark Aug 05 '12 at 21:08
  • I referenced it in http://www.dereuromark.de/2012/08/06/namespaces-in-vendor-files-and-cake2-x/ – mark Aug 06 '12 at 09:23
  • How about in cakephp 1.2 and 1.3 – Louie Miranda Dec 04 '12 at 00:47
  • One note: you should "return" after the include. Someone mentioned that on the referred blog article. – mark Aug 06 '13 at 16:26