PHP class upload

0

Greetings to all, I come again with a problem that I have with self-loading classes with spl_autoload.

This is my Autoloader class:

class Autoloader {
    static public function CargarClases($className) {
        $filename = "../classes/" . str_replace('\', '/', $className) . ".php";
        if (file_exists($filename)) {
            include($filename);
            if (class_exists($className)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('Autoloader::CargarClases');

This is a code that I got and it worked fine, but when I changed the code to use ajax and made a directory of drivers I stopped working, I do the class include in my index.php file, but I have had to add the include autoloader in the controllers, in each of them I do this:

require_once("../classes/Autoloader.php");

I do not know what I'm failing, what is the best practice to place this file and where to include it, I'm a little lost with this topic.

Greetings and I hope you can help me

    
asked by Mixzplit 15.12.2016 в 15:24
source

1 answer

2

It is best to define a constant in the index.php so const APP_DIR = __DIR__; with this you handle the correct path wherever you are. In my case what I have done is create an extra file called init.php in this define the constant APP_DIR and do the include of the autoload.php and the function files that I will need. Take into account that the autoloader must use the defined constant to avoid inclusion errors.

My init.php file looks like this:

<?php

const APP_DIR = __DIR__;

// autoload
require __DIR__ . '/includes/autoload.php';
require __DIR__ . '/vendor/autoload.php';

// functions
require __DIR__ . '/includes/functions/html.php';
require __DIR__ . '/includes/functions/util.php';
// ...

Then my file index.php has been like this:

<?php

require 'init.php';

// procesar la solicitud
//   detectar el controlador
//   detectar el action (función de la clase controladora que sera llamada
//   instanciar el objeto controlador y ejecutar la función

Using the index.php as the only point of entry for the application is a good practice. With this approach you can implement it and also in special cases (where you do not want to use the index.php) you can simply include the init.php and you have your application ready to run.

One more detail. Do not use the class_exists within the autoload. For me it is being redundant because the file already exists. In any case, if you decide to use it, pass the second parameter in false like this: class_exists($className, false); with this you tell class_exists not to use autolaod.

I hope it serves you! B-)

    
answered by 15.12.2016 / 17:05
source