I am implementing a autoloader
given the following scenario:
Structure:
There is an X Application that through FTP generates a structure of directories and php files: Example:
Where:
index.php
: would be the controller.
libs
: is the directory where the X application connects and creates the structure.
p_xxxx
: is the directory for each form, from 0001
to 9999
.
process.php
: is the file php
where the logic of the form is developed p_xxx
.
lista.php
: is the file php
where the html view of the form is developed p_xxx
.
According to the documentation, for a class file with this structure:
process.php
<?php
namespace Prueba\Dinamico\p_0001;
class Process
{
public function Ejemplo(){
echo 'process: p_0001';
}
}
my index should look like this:
index.php
<?php
namespace Prueba\Dinamico;
/**
* En esta sección es donde se agrega el formulario:
* p_0001
* pero se supone que este valor se recibe desde una variable de sesión del usuario:
* $_SESSION['currentForm']='p_0001';
*
* entonces la linea de código del use no logro implementarla de forma dinámico:
* y que cumpla con el PSR-4 y 12
*
*/
use Libs\p_0001\Lista;
spl_autoload_register(function ($clase) {
$file = strtolower(str_replace('\\', DIRECTORY_SEPARATOR, $clase)).'.php';
if(file_exists($file)){
require_once $file;
}else{
echo 'no se pudo cargar la Librería para esta Gestión.';
die;
}
});
$EjemploClase = new Lista();
$EjemploClase->Ejemplo();
The problem
As you can see, use Libs\p_0001\Lista;
it's static. I don't know how to access, for example p_0003
, the needed node, implementing $_SESSION['currentForm']
which is where the value of the form is saved, e.g.: p_0003
.
I don't know how to implement this and at the same time maintain the PSR 4 and 12 standard, since if I use or implement Magic Methods, the IDE does not recognize what is programmed as it is a value that changes at run time.
So far I have done research on this topic and php does not provide support for building namespaces in real time: Example:
There is no way for something like this to work right now. so how to fix this; the only way is by creating the instance from a variable:
No problem was found running this last example. The problem then in the development environment is with the tools:
1- Sublime Text 3 and 4: the go to definition option works correctly in the method
Ejemplo()
based on a full text search.2- PHPStorm: does not provide support to go to the definition or where the method is implemented.
Note: I appreciate those who leave in the comments tests with other editors or IDE.