0

this is my php folder/file structure:

mvc
    controller
        login.class.php
    model
        login.class.php
lib
    login.class.php
core
    controller.class.php
    model.class.php
    core.class.php

core.class.php code

<?php
class core
{
    public static function load()
    {
        require_once('lib.class.php');
        require_once('controller.class.php');
        require_once('model.class.php');
    }
}
core::load();
?>

i don't know where to set namespaces to do something like this:

\LIB\login.class.php
\CONTROLLER\login.class.php
\MODEL\login.class.php

thank you :)

3 Answers 3

2

You have to define the namespace as the first statement in every file (namespace my\namespace;). When the namespace matches the folder you can use the following autoloader to automagically load the needed files:

spl_autoload_register(function ($className) {
    $namespaces = explode('\\', $className);
    if (count($namespaces) > 1) {
        $classPath = APPLICATION_BASE_PATH . implode('/', $namespaces) . '.class.php';
        if (file_exists($classPath)) {
            require_once($classPath);
        }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

i don't like autoloaders... another way i have an error i use namespace in the first line but then i can't instance CORE classes like new DOMDocument etc... Fatal error: Class 'LIB\DOMDocument' not found, how i can use core classes inside namespaced file?
1

Namespace declarations go at the top of the file:

<?php
namespace Foo;

Comments

1
mvc
    controller
        login.class.php
    model
        login.class.php
lib
    login.class.php

index.php

mvc/controller/login.class.php

<?php
namespace controller;
require_once('mvc/model/login.class.php');
class login
{
    public function __construct()
    {
        $login = new \model\login();
    }
}
?>

mvc/model/login.class.php

<?php
namespace model;
require_once('lib/login.class.php');
class login
{
    public function __construct()
    {
        $login = new \lib\login();
    }
}
?>

lib/login.class.php

<?php
namespace lib;

class login
{
    public function __construct()
    {
        // core class instance
        $login = new \DOMDocument();
    }    
}
?>

index.php

<?php
require_once('mvc/controller/login.class.php');

$login = new \controller\login();
?>

Comments

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.