Introduction
The dependencies package is a simple package which allows you to sort dependencies, be it assets, simple strings, or class instances. It's clever enough to avoid circular dependencies in a never-ending loop.
The package requires PHP 7.2+ and follows the FIG standard PSR-0 to ensure a high level of interoperability between shared PHP code and is unit-tested.
Installation
The best and easiest way to install the Dependencies package is with Composer.
Preparation
Open your composer.json
file and add the following to the require
array:
"cartalyst/dependencies": "^2.0"
Note: Make sure that after the required changes your
composer.json
file is valid by runningcomposer validate
.
Install the dependencies
Run Composer to install or update the new requirement.
php composer install
or
php composer update
Now you are able to require the vendor/autoload.php
file to autoload the package.
Usage
In this section we'll show how you can make use of the extensions package.
Basic Usage
use Cartalyst\Dependencies\DependencySorter;
$sorter = new DependencySorter();
// Add a "foo" item who depends on "bar" and "baz"
$sorter->add('foo', ['bar', 'baz']);
$sorter->add('baz');
$sorter->add('bar', 'baz');
var_dump($sorter->sort()); // Will spit out ['baz', 'bar', 'foo']
// Circular dependencies are recognized and an exception
// will be thrown rather than a never-ending sorting loop.
$sorter->add('foo', ['bar', 'baz']);
$sorter->add('baz');
$sorter->add('bar', 'foo');
var_dump($sorter->sort());
// UnexpectedValueException: Item [foo] and [bar] have a circular dependency.
DependentInterface
Our sorter also has the ability to take classes which implement Cartalyst\Dependencies\DependentInterface. Let's use the following, simplified asset example:
use Cartalyst\Dependencies\DependencySorter;
use Cartalyst\Dependencies\DependentInterface;
class Asset implements DependentInterface
{
protected $slug;
protected $path;
protected $dependencies = [];
public function __construct(string $slug, string arra $path, $dependencies = [])
{
$this->slug = $slug;
$this->path = $path;
$this->dependencies = $dependencies;
}
public function getSlug(): string
{
return $this->slug;
}
public function getDependencies(): array
{
return $this->dependencies;
}
public function getPath(): string
{
return $this->path;
}
}
// Queue assets in a Dependency Sorter instance
$sorter = new DependencySorter([
new Asset('bootstrap', 'js/bootstrap-2.3.1.js', 'jquery'),
new Asset('jquery', 'js/bootstrap-1.9.1.min.js'),
new Asset('main', 'js/main.js', ['jquery', 'bootstrap']),
]);
$assets = $sorter->sort();
// In your view
@foreach ($assets as $asset)
<script src="{{ $asset->getPath() }}"></script>
@endforeach