Is it possible to include more than one.php file in the path of a Require?

Asked

Viewed 988 times

2

I didn’t know the best way to ask that question, but I came across the following question...

Inside a document, I have some require_once (that I was mounting for a while), in the code they are this way:

<?php
   require_once("diretorio/arquivo.php");
   require_once("diretorio/arquivo2.php");
   require_once("diretorio/arquivo3.php");
?>

It is possible that instead of replicating a require_once, I do it the way I will leave it below?

<?php
   require_once("diretorio/arquivo.php", "diretorio/arquivo2.php", "diretorio/arquivo3.php");
?>

Whether or not it is possible, what would be the best way to structure all these require? One per line or all in one?

  • 2

    At my suggestion, make an inc.php file where you add all require’s, stating the complete relative address. Dai, whenever you need to make a require for some files, just set it to the inc.php.

  • 1

    Because it doesn’t matter of a file that contains all the files?

  • 1

    Good idea, this doubt arose me because everything presents itself inside a document (at the top) and sometimes it bothers me to see some 3 busy lines with 20 characters. I’m trying to adapt to the best code rules right now.

  • Yeah, since you’re on top of someone else you just import it ;)

  • 1
  • Anyway, I can’t put multiple routes inside a require, right?

  • What do you call a route? it is possible to exchange that string for a variable or a constant yes!

  • What I mean is if there is any way to avoid replicating "require_once" and define only one with all paths. Or what would be the right way to do it, anyway, it was just a random question.

  • 1

    I get it, if the main files are in the same folder, you can list all these files and use one foreach to mount the require.

Show 4 more comments

3 answers

5


Let’s say all your includes files are in a folder the part called includes and your index at the project root, you can create a function that does all these requires/includes.

Use glob() to list all php files from includes and make a foreach.

Project structure:

Root 
   includes
   public
      html
      css
      js
index

This function must be in your index or config.

<?php

function includes(){
    foreach(glob('includes/*.php') as $arquivo){
        require_once $arquivo;
    }
}

includes();

Do a quick test create 2 or 3 files in the includes folder with the following content:

<?php
echo __FILE__ .'<br>';

Then call your index and see the result, something like:

projeto\includes\1.php
projeto\includes\2.php
projeto\includes\3.php

You can also create a file with constants from the main directories and pass one of them in place of that folder that is fixed in glob().

4

Instead of using manual includes, because you don’t use an autoload for all required classes?

define('PS', PATH_SEPARATOR);
define('DS', DIRECTORY_SEPARATOR);
set_include_path(get_include_path() . PS . 'diretorio' . DS);
spl_autoload_extensions('.php, .inc');
spl_autoload_register();

You can do this to limit the files "suaclasse.class.php":

define('PS', PATH_SEPARATOR);
define('DS', DIRECTORY_SEPARATOR);
define('CLASS_DIR', 'class' . DS);
set_include_path(get_include_path() . PS . CLASS_DIR);

// se quiser atribuir um "class" aos arquivos `/class/file.class.php`
spl_autoload_extensions('.class.php');

spl_autoload_register();

In fact, as @Wallacemaxters observed, the correct is to use: PATH_SEPARATOR

There is another interesting way to do that is through the use of Composer.phar:

keeping the file: Composer.json

{
    "name": "empresa/seuapp",
    "description": "Nome do APP",
    "require": {
        "phpunit/phpunit": "^4",
        "php": ">=5.3.3"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "seunome",
            "email": "[email protected]"
        }
    ],
    "minimum-stability": "alpha",
    "config": {
        "vendor-dir": "vendor/"
    }, 
    "autoload": {  
        "psr-4": {
            "SeuApp\\": ["src/"]
        }
    },
    "comments": [
                 "- Para habilitar o autoload, use o comando: php composer.phar dump-autoload -o",
                 "- Para instalar o composer: php composer.phar install",
                 "- Para atualizar o composer: php composer.phar self-update",
                 "- Servidor web embutido: php -S localhost:9000 -t /var/www/html/seuapp/public"
                 ]
}

Create the folders:

/SeuApp/public/
/SeuApp/src/
/SeuApp/src/Controller/
/SeuApp/test/

Inside the Controller folder, include the file ApplicationController.php:

<?php

namespace SeuApp\Controller;

class ApplicationController
{
    public function controller()
    {
     return 'Olá Mundo';
    }
}

And at the root of /SeuApp/src, the file, Application.php with:

<?php

namespace SeuApp;

class Application extends Controller\ApplicationController
{

    public function index()
    {
       echo self::controller();
    }
}

Ready, you already have the basics of an application using Autoload from Composer.

  • I didn’t know that one, Ivan! + 1

  • Opa, for this I did not expect, I will put into practice too. Thanks Ivan!

  • 2

    Ivan, I think there’s just one small mistake. You don’t use the DIRECTORY_SEPARATOR in that case, and yes PATH_SEPARATOR. Because then php will create a list of directories that may have the paths included. The output has to look like this: "www/var;www/php;www/meu_project;". And that depends on the operating system. So you have to use the constant

  • But regardless of being DIRECTORY_PATH or PATH_SEPARATOR, they are not considered portable codes?

  • 1

    @Wallacemaxters, I’m used to making applications using the autoload of Composer, which would also be applicable in this situation.

  • I also prefix using the composer. He already does everything for me, just give the command ;)

Show 1 more comment

3

To assist the response of @rray, reinforcement the idea of you using a function of glob united with include/require

function glob_include($glob, $flag = 0) {
    foreach (glob($glob, $flag) as $file) {
         require_once $file;
    }
}

The use would be:

glob_include('diretorio/*.php');

Still another option is to use GlobIterator.

$it = new GlobIterator('diretorio/*.php');

foreach ($it as $file) {
    require $file->getRealpath();
}

In that case, I’d rather use getRealpath, because the path to be passed is absolute. I’ve heard it has its advantages ;)

  • Opa this function call got good :D, what is the $flag =0 ?

  • 1

    @rray, Glob has parameters like GLOB_BRACE. So you can do glob('/dir/*.{txt,php,js,css}'). That will list txt,php,js e css in the same glob ;)

  • A filter, I got it. Tbm hadn’t noticed q was the signature of the xD function

  • 1

    Too bad you can’t use it on GlobIterator. He’s better, because he doesn’t save everything in one array.

Browser other questions tagged

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