CacheServiceProvider.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Libs\TikTok\Kernel\Providers;
  3. use Pimple\Container;
  4. use Pimple\ServiceProviderInterface;
  5. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  6. use Symfony\Component\Cache\Adapter\RedisAdapter;
  7. /**
  8. * Class CacheServiceProvider.
  9. * 支持多样的缓存配置,在配置中新增cache字段,具体配置见文档。项目建议使用Redis做缓存,可以提升效率。
  10. */
  11. class CacheServiceProvider implements ServiceProviderInterface
  12. {
  13. /**
  14. * Registers services on the given container.
  15. *
  16. * This method should only be used to configure services and parameters.
  17. * It should not get services.
  18. *
  19. * @param Container $pimple A container instance
  20. */
  21. public function register(Container $pimple): void
  22. {
  23. !isset($pimple['cache']) && $pimple['cache'] = static function ($app) {
  24. $config = $app->getConfig();
  25. if (!empty($config['cache']) && !empty($config['cache']['type'])) {
  26. switch (strtolower($config['cache']['type'])) {
  27. case "redis":
  28. $dsn = 'redis://';
  29. if (!empty($config['cache']['password'])) {
  30. $dsn .= "{$config['cache']['password']}@";
  31. }
  32. if (!empty($config['cache']['host'])) {
  33. $dsn .= $config['cache']['host'];
  34. } else {
  35. $dsn .= '127.0.0.1';
  36. }
  37. if (!empty($config['cache']['port'])) {
  38. $dsn .= ":{$config['cache']['port']}";
  39. } else {
  40. $dsn .= ":6379";
  41. }
  42. if (!empty($config['cache']['select'])) {
  43. $dsn .= "/{$config['cache']['select']}";
  44. }
  45. if (empty($config['cache']['prefix'])) {
  46. $config['cache']['prefix'] = 'EasyTiktok';
  47. }
  48. return new RedisAdapter(RedisAdapter::createConnection($dsn), $config['cache']['prefix']);
  49. default:
  50. return new FilesystemAdapter('EasyTiktok', 1500);
  51. }
  52. } else {
  53. return new FilesystemAdapter('EasyTiktok', 1500);
  54. }
  55. };
  56. }
  57. }