Skip to content
This repository has been archived by the owner on May 12, 2022. It is now read-only.

nickolasburr/ezimports

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

66 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ezimports

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 to vendor/nickolasburr/ezimports.
  • <VENDOR>_<MODULE>_IMPORTS_FILE_NAME: Imports file basename. Defaults to imports.json.
  • <VENDOR>_<MODULE>_IMPORTS_FILE_PATH: Imports file path. Defaults to vendor/<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.

About

Register PHP file imports via JSON.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages