Search code examples
phppsr-0

How do I use the SplClassLoader


I am trying to understand and use the PSR-0 Autoloader. But it doesn't work.

My Folder structure:

Core/

  • Library/
  • Model/

My index.php in Root

<?php
require_once 'Core/Library/SplClassLoader.php';

$loader = new SplClassLoader('Core', 'Core');
$loader->register();



use Model\Post;

Post.php in Model folder.

<?php
namespace Model;

class Post implements PostInterface
{
// ...

PostInterface

<?php
namespace Model;

interface PostInterface
{
//...

I Get the following error:

Fatal error: Class 'Model\Post' not found in C:\wamp\www\Test\index.php on line 17

Line 17: Init new Post;

What am I doing wrong here?


Solution

  • SplClassLoader works like this:

    $loader = new SplClassLoader('NamespaceName', 'path/To/Base/Directory');
    

    You are registering Core namespace here, but you don't have Core\Model namespace, but simply Model