nickolasburr / ezimports
Register PHP imports at runtime.
Requires
- php: >=7.1
This package is auto-updated.
Last update: 2022-05-28 02:12:28 UTC
README
Register PHP imports via JSON.
Table of Contents
Installation
composer require nickolasburr/ezimports
Configuration
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.
Constants
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
.
Usage
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'); }
Benefits
- Reduce SLOC of PHP source files
- Map dependencies via JSON instead of parsing PHP files
Caveats
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.