Register PHP imports via JSON.
composer require nickolasburr/ezimports
The imports JSON file should contain an array of objects, each representing an entity and its subsequent imports. For each entity object, the following properties should be specified:
class
: The FQCN of the class, interface, or trait.imports
: An array of import objects.use
: The FQCN of the class, interface, or trait to import.as
: [OPTIONAL] The alias to use in place of the short name. Defaults to short name.
Prior to searching, ezimports looks for the following constants:
EZIMPORTS_MODULE_PATH
: The path to the ezimports module directory. Defaults tovendor/nickolasburr/ezimports
.<VENDOR>_<MODULE>_IMPORTS_FILE_NAME
: Imports file basename. Defaults toimports.json
.<VENDOR>_<MODULE>_IMPORTS_FILE_PATH
: Imports file path. Defaults tovendor/<VENDOR>/<MODULE>/imports.json
.
Instead of including imports statically:
<?php
namespace Example;
use Dictionary\WordInterface;
use External\Entity;
use Somewhere\Outside\ThisNamespace as Outsider;
class Name implements WordInterface
{
}
Invoke include_imports
with FQCN and module name:
<?php
declare(strict_types=1);
namespace Example;
\include_imports(Name::class, '<VENDOR>/<MODULE>');
class Name implements WordInterface
{
}
Next, add the imports to imports.json
in the module root directory:
[
{
"class": "Example\\Name",
"imports": [
{
"use": "Dictionary\\WordInterface"
},
{
"use": "External\\Entity"
},
{
"use": "Somewhere\\Outside\\ThisNamespace",
"as": "Outsider"
}
]
}
]
Alternatively, specify the path via <VENDOR>_<MODULE>_IMPORTS_FILE_PATH
.
The easiest way to achieve this is to add a bootstrap file to the module,
which can be loaded first.
<?php
/**
* bootstrap.php
*
* As an example, assume the module is
* named 'nickolasburr/testmodule'.
*/
if (!defined('NICKOLASBURR_TESTMODULE_IMPORTS_FILE_PATH')) {
define('NICKOLASBURR_TESTMODULE_IMPORTS_FILE_PATH', '/path/to/module/imports.json');
}
- Reduce SLOC of PHP source files
- Map dependencies via JSON instead of parsing PHP files
Just like anything else, there are tradeoffs, such as:
- Less performant (no formal benchmarks currently)
- Less secure (but not insecure when managed properly)
In reality, it's probably better to just stick with static imports.