G
G
grabbee2014-05-29 16:35:03
PHP
grabbee, 2014-05-29 16:35:03

How to correctly use namespace autoloading of php classes?

It's hard for me, because I took an article from habra habrahabr.ru/post/150267 as an example - in which autoload is not used, and in other articles autoload is used with a different file structure. I deal with both, it's very difficult.

<?php
class Autoloader
{ 
 
    public static $loader;

    public static function init()
    {
        if (self::$loader == NULL)
            self::$loader = new self();

        return self::$loader;
    }

    public function __construct()
    {
        spl_autoload_register(array($this, 'autoload'));
    }

    public function autoload($className)
    { 
        //echo $className."\n";   
                    
        $path = str_replace('\\', DS, $className); 
         require_once(PATH_APP.DS.$path.'.class');
                              
    }
}

There is such a project structure.
fbe78972d8669ee4cadf547e35b383dc.pngfb79d5b3be814853c9e36d62e4817efc.png28e4a4a1d2a70c4a54a5df4a93ed5459.png
I decided to try namespace in classes, but I'm afraid to get confused
<?
namespace core;

class View
{

<?  
namespace contr;

class contr_index extends \core\Controller
{
   
    function __construct()
    {                             
     $this->model = new \model\model_index();
     $this->view  = new \view\view_index();
    }
    
    function action_index()
    {
     $data = $this->model->get_data();    
     $this->view->generate('view_index.php', 'template_view.php', $data);
    }
}

<?
namespace model;

class model_index extends \core\Model
{
 
    public function get_data()

Am I doing everything right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Veliko-Ivanenko, 2014-05-29
@grabbee

www.php-fig.org/psr/psr-0

D
Dmitry Korshunov, 2014-05-29
@dkorshunov55

Although the issue is resolved, but still:
Confused with Autoloader & NAMESPACE <- here is the solution.
And here in Russian about PSR, etc.:
getjump.github.io/ru-php-the-right-way

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question