T
T
thorii2016-08-20 15:56:52
PHP
thorii, 2016-08-20 15:56:52

CacheProvider, what standards and practices to use when writing in php?

CacheProvider, what standards and practices to use when writing in php?
Actually, I conceived the cache provider only as a class of a single caching API, but the question arose, how to specify a driver for working with the cache?
At the moment I have this:

<?php
$cache = new CacheProvider(CacheProvider::DRIVER_REDIS, $configRedis);
$cache->set('key', 'value');
?>

The question is: Is it critical to use constants to identify a driver? That is, identification constants are written in the class itself:
const DRIVER_REDIS = 0;
const DRIVER_MEMCADHED = 1;
const DRIVER_FILE = 2;

According to these IDs, the driver class path is loaded from the config in the constructor and its instance is created:
Cache.Config.php
<?php
$config = array(
  'drivers' => array(
    '0' => array(
      'name' => 'RedisDriver',
      'lib' => '\Architect\Cache\Drivers\RedisDriver'
    ),
    '1' => array(
      'name' => 'MemcachedDriver',
      'lib' => '\Architect\Cache\Drivers\FileDriver'
    ),
    '2' => array(
      'name' => 'FileDriver',
      'lib' => '\Architect\Cache\Drivers\FileDriver'
    )
  )
);
?>

When adding drivers, you have to write an identification constant. Can rewrite on a named constructor?
$cache = CacheProvider::driver('REDIS');
$cache->set('key', 'value');

Or am I just paranoid for nothing and I need to get rid of the constants and write the name of the driver as a string?
$cache = new CacheProvider('REDIS', $driverConfig);

PS I am very sensitive to the little things.
-Spy on Doctrine/Symfony/Laravel/YII/CI please don't suggest.
Is a named constructor used in such cases?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Kulikovsky, 2016-08-20
@by25

It's better to create a concrete instance of a class like RedisCacheProvider that implements a common interface like CacheProviderInterface.
You can peek here: https://github.com/doctrine/cache
Also, I would put the creation of objects in a DI container. And read about dependency inversion (if necessary).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question