0

I am creating my own MVC framework for a simple website and I want to use namespaces but I don't know how to autoload them. Here is what I tried so far:

I have a init.php file that has autoloading function:

    spl_autoload_register(function($class){
    $file = __DIR__ . '/../' . str_replace('\\', '/', $class) .'.php';
    echo $file;
    if (file_exists($file)) {
        require_once $file;
        echo 'yes';
    }

    use App\Core\App as App;

    $app = new App;

This code returns "yes" so it locates the App file.. But it also returns a fatal error: D:\xampp\htdocs\MVC\App/../App/Core/App.phpyes Fatal error: Class 'App\Core\App' not found in D:\xampp\htdocs\MVC\App\init.php on line 28 Line 28 is $app = new App;

Here is how I am namespacing my App file:

    <?php

    namespace App\Core\App;

    class App 
    {
    .....

The file structure is the following:

| App
|--| Core
|--|--| App.php
...
| init.php

Any ideas why?

9
  • It could be the directory path, is it D:\xampp\htdocs\MVC\App\App\Core\App.php? Commented Sep 10, 2017 at 18:45
  • No it is D:/xampp/htdocs/MVC/App/Core/App.php Commented Sep 10, 2017 at 18:46
  • Then like Chris says your need to change your namespace or fix the directory structure. It's echoing out what it is. D:\xampp\htdocs\MVC\App/../App/Core/App.php Commented Sep 10, 2017 at 18:47
  • 2
    The namespace for your class App should be namespace App\Core; Commented Sep 10, 2017 at 18:48
  • 1
    If your namespace is namespace App\Core\App; and your class is App it would be $app = new App\Core\App\App(); can you see how that's confusing lol Commented Sep 10, 2017 at 18:51

1 Answer 1

1

Instead of making your own autoloader, just use the one, that comes built-in with composer. You just add the following segment in the composer.json file and it's done:

"autoload": {
  "psr-4": {
    "": "dir_where_namespaces_start...usually_src"
  }
}

Also, you can't really make and "mvc framework", because MVC architecture is what the application code implements and no the framework.

Sign up to request clarification or add additional context in comments.

1 Comment

This is genius and works like a charm! Didn't know that you can do this with composer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.