__autoload PHP function does not open subfolders

Asked

Viewed 739 times

1

I have a __autolader function that should take the folder ['Conn','etc'], but it does not work on my Ubuntu 14.04 Lamp environment, and works well on Windows 7 WAMP. I have done several debugs without result, how to solve this problem?

function __autoload($Class) {

    $cDir = ['Conn'];
    $iDir = null;

    foreach ($cDir as $dirName):
        if (!$iDir && file_exists(__DIR__ . "\\{$dirName}\\{$Class}.class.php") && !is_dir(__DIR__ . "\\{$dirName}\\{$Class}.class.php")):
            include_once (__DIR__ . "\\{$dirName}\\{$Class}.class.php");
            $iDir = true;
        endif;
    endforeach;

    if (!$iDir):
        trigger_error("Não foi possível incluir {$Class}.class.php", E_USER_ERROR);
        die;
    endif;
}

3 answers

2

OK! Get it right! Reversing the rods now!! Tip!

foreach ($cDir as $dirName):
        if (!$iDir && file_exists(__DIR__ . "//{$dirName}//{$Class}.class.php") && !is_dir(__DIR__ . "//{$dirName}//{$Class}.class.php")):
            include_once (__DIR__ . "//{$dirName}//{$Class}.class.php");
            $iDir = true;
        endif;
    endforeach;
  • 1

    could use the function realpth() to "canonize".

  • 1

    Almost there... Canonize ^_^

  • @Danielomine almost there² : realpath() xD

  • haha sorry, I didn’t know how to write in English, so I put in quotes.

2


To avoid bar type problems, you can use the preset constant DIRECTORY_SEPARATOR thus:

foreach ($cDir as $dirName):
    if (!$iDir && file_exists($file = __DIR__ . DIRECTORY_SEPARATOR . $dirName . DIRECTORY_SEPARATOR . $Class . '.class.php') && !is_dir($file)):
        include_once ($file);
        $iDir = true;
    endif;
endforeach;

This ensures compatibility between different systems...

A hurrah to Windows that accepts any type of bar!!! o/

2

If you no longer want to have problems with this type of situation I recommend using an Autoloader ready. My tip is to use the Composer, for this you have to install the same.

Installing the Composer

To install Composer just run a command line, nothing else! There are other ways to install Composer, more I’ll show you what I like the most.

Run the following command at the root of your project:

$ curl -sS https://getcomposer.org/installer | php

Or

php -r "readfile('https://getcomposer.org/installer');" | php

Remembering that if you use the second option you have to run PHP for it put its folder in environment variables or pass its path when executing the command.

Ready now you have Composer installed in your project! Now we just need to ask him to install the dependencies in his project and when installing the dependencies he will install an Autoloader automatically.

Installing the dependencies

First you have to have the Composer configuration file. At the root of your project create the following file:

Composer.json

{
    "name": "fabio/autoload",
    "description": "Ensinando Autoload",
    "type": "project",
    "license": "MIT",
    "authors": [
        {
            "name": "Fábio Lemos Elizandro",
            "email": "[email protected]"
        }
    ],
    "autoload": {
        "psr-0": {
            "": ""
        }
    },
    "require": {}
}

Note that I did not declare any dependency because I am only interested in Autoloader. After creating this file run the following command at the root of your project:

$ php composer.phar install 

Or

$ php composer.phar update

That will depend on your intention.

Alternate configuration

You can configure your project’s Autoloader, a configuration I use is as follows::

"autoload": {
        "psr-0": {
            "": "src/"
        }
    },

Now I can leave my sources inside the directory without having to include it in the namespace.

Using the Autoloader

I’ll leave an example of simple usage which is an index.php instantiating a class

Example class

//src/Response.php
class Response 
{
    private $content;

    public function setContent($content)
    {
        $this->content = $content;
    }
    public function flush()
    {
        echo $this->content;
    }
}

Index

//index.php
require "vendor/autoload.php";

$response = new Response();

$response->setContent('teste');
$response->flush();

NOTE: This mini tutorial is valid for PHP >= 5.3, I don’t know how it is for older versions

  • Missed the most important: require_once('vendor/autoload.php') on the public page that will run your application. Or the idea is to expose the entire application code in the public folder? It’s interesting to use a ready-made implementation, but it’s even more interesting to know how it works.

  • Note: if not working with code that needs to work in php versions without namespace support (< 5.2) prefer to use to PSR-4.

  • @gmsantos really forgot to set the example

  • @gmsantos never used PHP less than 5.3, so I put a note at the end of the reply. Thank you

  • Even with editing, prefer psr4 instead of psr0.

  • @gmsantos removed comment on psr

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.