Skip to content

Instantly share code, notes, and snippets.

@sasezaki
Last active December 17, 2015 17:09
Show Gist options
  • Select an option

  • Save sasezaki/5644402 to your computer and use it in GitHub Desktop.

Select an option

Save sasezaki/5644402 to your computer and use it in GitHub Desktop.
crazy heroine sample
<?php
namespace Sample;
use Heroine\Heroine;
use Heroine\Factory\FactoryInterface;
use PDO;
// heroine is here
// https://github.com/bjyoungblood/heroine
require_once __DIR__.'/test/bootstrap.php';
$config = [
'pdo' => [
'db' => 'mysql',
'dbname' => 'hoge',
'host' => 'localhost',
'user' => 'dbusername',
'password' => 'dbpassword',
],
];
$authorized = false;
class User
{
public $id;
public $point;
}
class AuthorizedGameService
{
private $pdo;
public function __construct($pdo)
{
$this->pdo;
}
public function givePoint($user, $point)
{
// some stuff
}
}
class GameServiceFactory implements FactoryInterface
{
public function createService(Heroine $heroine, $service)
{
return new $service($heroine->get('pdo'));
}
}
$heroine = new Heroine([
'instantiables' => [
'user' => 'Sample\User',
],
'factories' => [
'Sample\GameService' => 'Sample\GameServiceFactory',
'Sample\AuthorizedGameService' => 'Sample\GameServiceFactory',
],
'callables' => [
'pdo' => function (Heroine $heroine) use ($config) {
$pdo = $config['pdo'];
$dsn = "{$pdo['db']}:dbname={$pdo['dbname']};host={$pdo['host']}";
return new PDO($dsn, $pdo['user'], $pdo['password']);
}
],
'initializers' => [
function (Heroine $heroine, $instance) use ($authorized) {
if ($instance instanceof AuthorizedGameService) {
if (!$authorized) {
throw new \Exception();
}
// then hydrate User
$user = $heroine->get('user');
$user->id = $authorized->id;
}
}
]
]);
var_dump($heroine->get('Sample\AuthorizedGameService')->givePoint($heroine->get('user'), 100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment