Thursday, January 6, 2022

[FIXED] How to include class?

Issue

handlers/
     handler.php
src/
     Model.php

I'm trying include class Model.php

<?php 
declare(strict_types=1);

namespace App;

class Model{
    }

handler.php

<?php 
include_once($_SERVER['DOCUMENT_ROOT'].'/src/Model.php');

$model=new Model();

I get an error:

Class 'Model' not found

Is it because I am using composer autoloader?

"autoload": {
        "psr-4": {
            "App\\": ["src/"]


        }
    },

Solution

Model.php

<?php 

declare(strict_types=1);

namespace src;

class Model{}

Handler.php

<?php 
    
use src\Model;

require __DIR__ . '../vendor/autoload.php'; // or whatever to route is to your autoload file

$model=new Model();

The final thing I want to mention is that the directory specified in the autoload file should be a folder that contains all of your classes ideally. Beyond that, the namespaces should be subdirectories in the directory where that class can be located. So say you have the folder Classes, and then src may be under it, you would do:

"autoload": {
    "psr-4": {
        "": "Classes/"
    }
},

namespace src;

This works if your class is in the src folder. If you added a subfolder of src with your class in it:

namespace src\subfolder;


Answered By - solidforge

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.