larzone/hinnyuu

There is no license information available for the latest version (v2.3.0) of this package.

dependency manager

v2.3.0 2016-07-14 14:14 UTC

This package is auto-updated.

Last update: 2024-04-29 02:54:03 UTC


README

Hinnyuu uses reflection to build dependencies and invoke methods on a class. It caches all instantiated objects and only instantiates them once. As the name implies, it is a quite small utility library. For convenience, a function hinnyuu() can be used as a public interface to the class. The instance of the Hinnyuu class lives as a static variable within the function.

Basic usage

This will instantiate the concrete Database implementation with constructor arguments username and password (found by reflection).

<?php
namespace MyApp\Implementations {
    interface IDatabase { public function query($str); }
    class Database implements IDatabase { public function __construct($username, $password) {} public function query($str) { echo($str); } }
}
namespace MyApp {
    use MyApp\Implementations\IDatabase;
    use MyApp\Implementations\Database;
    use function Dekapai\Hinnyuu\Facade\hinnyuu;
    // register
    hinnyuu([IDatabase::class => Database::class]);
    // invoke a closure
    hinnyuu(function(IDatabase $db) { return $db->query("SELECT * FROM users"); }, ['username' => 'bill.gates', 'password' => 'susageP']);
}

Static methods

For factory and/or singleton classes, pass an array ['ClassName', 'methodName'] instead of the string ClassName.

<?php
// register interface to a concrete implementation
hinnyuu(['MyApp\Interfaces\IDatabase' => ['MyApp\Implementations\Database', 'makeInstance']]);

// invocation of MyMethod on class MyController (automatically resolves all dependencies)
$result = hinnyuu('MyController', 'MyMethod');

Event system

A minimalistic event system is implemented using two functions: attach(event, listener) and trigger(event). The listener class' constructor is run when the event identified by the event string is triggered using the trigger function. The event string doesn't have to refer to a class. The listener can be a class or a closure. Dependency injection is done in both cases.

<?php

attach(Event1::class, Listener1::class);
attach(Event1::class, Listener2::class);
trigger(Event1::class);

attach('some_event', function() { print "event happened"; });
attach('some_event', function(SomeDependency $d) { error_log(sprintf("[%d]log something maybe"), $d->getCode(); });
trigger('some_event');