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 :)

ZiTAL
  • 3,466
  • 8
  • 35
  • 50

3 Answers3

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);
        }
    }
});
TimWolla
  • 31,849
  • 8
  • 63
  • 96
  • 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? – ZiTAL Jan 28 '12 at 14:03
  • http://stackoverflow.com/questions/6901358/problems-with-php-namespaces-and-built-in-classes-how-to-fix – ZiTAL Jan 28 '12 at 14:54
1

Namespace declarations go at the top of the file:

<?php
namespace Foo;
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
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();
?>
ZiTAL
  • 3,466
  • 8
  • 35
  • 50