Skip to content

Instantly share code, notes, and snippets.

@alister
Last active September 27, 2017 14:11
Show Gist options
  • Save alister/6d149871170cdf0c769fa4f833aeb112 to your computer and use it in GitHub Desktop.
Save alister/6d149871170cdf0c769fa4f833aeb112 to your computer and use it in GitHub Desktop.
<?php
use AppBundle\SncRedis\ClientsListPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(/* listing bundles used in the app... */);
return $bundles;
}
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new ClientsListPass());
}
// ... other AppKernel functions
}
<?php
namespace AppBundle\SncRedis;
class ClientsList
{
private static $clients;
public function __construct()
{
self::$clients = array();
}
public function addRedisClient($id, $alias = null)
{
self::$clients[$alias] = $id;
}
public function getClient(string $alias)
{
if (array_key_exists($alias, self::$clients)) {
return self::$clients[$alias];
}
return null;
}
public function getClients()
{
return self::$clients;
}
}
<?php
namespace AppBundle\SncRedis;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
use AppBundle\SncRedis\ClientsList;
/**
* Find the services tagged 'snc_redis.client' and collect all the data
*
* The `addRedisClient` method isn't actually called yet. It will be only
* be run if `AppBundle\SncRedis\ClientsList` is used in the app.
*/
class ClientsListPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
// Register the service for storage of Redis Clients
$container->register(ClientsList::class, ClientsList::class);
$definition = $container->findDefinition(ClientsList::class);
// find all service IDs with the snc_redis.client tag
$taggedServices = $container->findTaggedServiceIds('snc_redis.client');
foreach ($taggedServices as $id => $tags) {
// a service could have the same tag more than once
foreach ($tags as $attributes) {
$definition->addMethodCall('addRedisClient', array(
new Reference($id),
$attributes["alias"]
));
}
}
}
}
<?php
// .....
// Show the list of snc_redis clients:
$sncRedisClients = $this->getContainer()->get(ClientsList::class);
$arrayOfSncRedisClients = $sncRedisClients->getClients();
$redisInfo = [];
foreach ($arrayOfSncRedisClients as $alias => $redis) {
$redisInfo[] = [$redis->getDbNum(), $alias];
}
$table = new Table($output);
$table
->setHeaders(array('dbNum', 'Alias'))
->setRows($redisInfo);
$table->render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment