Showing posts with label Symfony. Show all posts
Showing posts with label Symfony. Show all posts

Tuesday, 1 October 2024

List of keys you can use in a Symfony services.yaml

Here’s a comprehensive list of keys you can use in a Symfony services.yaml file, along with brief descriptions for each:

1. Global Configuration Keys

  • parameters: Defines reusable parameters throughout the service definitions.

2. Service Definitions Keys

  • services: Main section where you define services.

Service Configuration Keys

  • class: The class name of the service being defined (if using the shorthand syntax).
  • arguments: Dependencies passed to the service constructor.
  • tags: Metadata tags for the service (e.g., event listeners, commands).
  • factory: Specifies a factory method to create the service.
  • decorates: Replaces a service with a decorated version.
  • bind: Specifies parameters for specific arguments in the constructor.
  • autowire: Automatically injects dependencies into services.
  • autoconfigure: Automatically configures services based on their interfaces or parent classes.

3. Parameter Configuration Keys

  • default_logger: Example of a parameter that can hold configuration values.
  • log_file: Default log file location or similar configuration values.

4. Service-Specific Configuration Keys

  • public: Determines whether the service can be accessed from outside the service container (default is true in Symfony 4.0 and later).
  • shared: Indicates if the service is a singleton (default is true).

5. Service Factory Configuration Keys

  • factory: Specifies the method that should be called to instantiate the service.

6. Service Alias Configuration Keys

  • aliases: Allows you to create aliases for services, enabling you to refer to a service by a different name.

7. Tags Configuration Keys

  • name: The name of the tag.
  • priority: Sets the priority of the tag, determining the order in which tagged services are processed.
  • attributes: Custom attributes that can be added to tags.

8. Additional Keys for Configuration

  • calls: Specifies methods that should be called on the service after it is constructed.
  • factory: Specifies a method that should be called to create the service.
  • deprecated: Marks a service as deprecated.
  • class: Defines the class name of the service being defined (if using shorthand syntax).

Example services.yaml with All Keys

Here’s a fictive example of how these keys can be used in a services.yaml file:

parameters: default_logger: '%env(APP_DEFAULT_LOGGER)%' log_file: 'app.log' services: App\Service\Logger\LoggerInterface: '@=service(parameter("default_logger"))' App\Service\Logger\DatabaseLogger: class: App\Service\Logger\DatabaseLogger arguments: $entityManager: '@doctrine.orm.entity_manager' tags: - { name: 'logger' } App\Service\Logger\FileLogger: class: App\Service\Logger\FileLogger arguments: $logFile: '%log_file%' public: false # Example of service visibility App\Service\UserService: autowire: true autoconfigure: true arguments: $logger: '@=service(parameter("default_logger"))' App\EventListener\SomeEventListener: tags: - { name: 'kernel.event_listener', event: 'kernel.request', method: 'onKernelRequest' } App\Service\SomeService: decorates: 'original.service.id' factory: ['@some.factory.service', 'create']

Summary of Keys

  • Global Keys: parameters
  • Service Keys: services, class, arguments, tags, factory, decorates, bind, autowire, autoconfigure, public, shared, aliases, calls, deprecated

This list and the example configuration should provide you with a comprehensive overview of the configuration keys available in Symfony's service container. If you need any further details or examples, feel free to ask!

Manage multiple types of logs in Symfony

Here’s the complete implementation that allows you to select a logger dynamically based on the APP_LOGGER_TYPE environment variable. This includes the logger interface, logger implementations, user service, user controller, and the service configuration in services.yaml.

1. Logger Interface

File: src/Service/Logger/LoggerInterface.php

namespace App\Service\Logger; interface LoggerInterface { public function log(string $message): void; }

2. File Logger Implementation

File: src/Service/Logger/FileLogger.php

namespace App\Service\Logger; class FileLogger implements LoggerInterface { private string $logFile; public function __construct(string $logFile = 'app.log') { $this->logFile = $logFile; } public function log(string $message): void { file_put_contents($this->logFile, $message . PHP_EOL, FILE_APPEND); } }

3. Database Logger Implementation

File: src/Service/Logger/DatabaseLogger.php

namespace App\Service\Logger; use Doctrine\ORM\EntityManagerInterface; use App\Entity\LogEntry; class DatabaseLogger implements LoggerInterface { private EntityManagerInterface $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function log(string $message): void { $logEntry = new LogEntry(); $logEntry->setMessage($message); $logEntry->setCreatedAt(new \DateTime()); $this->entityManager->persist($logEntry); $this->entityManager->flush(); } }

4. Email Logger Implementation (Optional)

File: src/Service/Logger/EmailLogger.php

namespace App\Service\Logger; class EmailLogger implements LoggerInterface { public function log(string $message): void { // Implement email logging logic here // e.g., sending an email with the log message mail('admin@example.com', 'Log Entry', $message); } }

5. User Service

File: src/Service/UserService.php

namespace App\Service; use App\Service\Logger\LoggerInterface; class UserService { private LoggerInterface $logger; public function __construct(LoggerInterface $logger) { $this->logger = $logger; } public function createUser(string $username): void { $this->logger->log("User $username created."); } }

6. User Controller

File: src/Controller/UserController.php

namespace App\Controller; use App\Service\UserService; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; class UserController extends AbstractController { private UserService $userService; public function __construct(UserService $userService) { $this->userService = $userService; } public function create(): Response { $this->userService->createUser('JohnDoe'); // Uses the injected logger return new Response('User created and logged.'); } }

7. Entity Class for Log Entry (Optional)

File: src/Entity/LogEntry.php

namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() */ class LogEntry { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private int $id; /** * @ORM\Column(type="string") */ private string $message; /** * @ORM\Column(type="datetime") */ private \DateTime $createdAt; public function setMessage(string $message): void { $this->message = $message; } public function setCreatedAt(\DateTime $createdAt): void { $this->createdAt = $createdAt; } }

8. Configure Services in services.yaml

File: config/services.yaml

parameters: log_file: 'app.log' # Default log file location services: # Conditional service based on APP_LOGGER_TYPE App\Service\Logger\LoggerInterface: '@=service("App\Service\Logger\\" . ucfirst(getenv("APP_LOGGER_TYPE")) . "Logger")' App\Service\Logger\DatabaseLogger: arguments: $entityManager: '@doctrine.orm.entity_manager' App\Service\Logger\FileLogger: arguments: $logFile: '%log_file%' # Use the default log file from parameters App\Service\Logger\EmailLogger: ~ # Add EmailLogger service if necessary App\Service\UserService: arguments: $logger: '@=service("App\Service\Logger\\" . ucfirst(getenv("APP_LOGGER_TYPE")) . "Logger")'

9. Update Your .env File

Set the desired default logger in your .env file:

File: .env

APP_LOGGER_TYPE=file # or database, or email

Summary

With this setup:

  • You can easily switch between different logging mechanisms by simply changing the value of APP_LOGGER_TYPE in your .env file.
  • The services.yaml configuration dynamically selects the appropriate logger implementation based on the environment variable, enabling you to use different logging strategies without modifying the service or application logic.

Publish npm package

  Để publish   pav-kit  lên NPM, bạn hãy làm theo các bước dưới đây. Tôi đã tạo thêm file  index.js  để đảm bảo gói tin hợp lệ. Bước 1: Tạo ...