php-symfonyHow to use Data Transfer Objects (DTO) with PHP Symfony?
Data Transfer Objects (DTOs) are used to transfer data between layers of an application. In PHP Symfony, DTOs are used to transfer data between the controller and the view.
Example code
// src/DTO/UserDTO.php
namespace App\DTO;
class UserDTO
{
public $name;
public $email;
}
// src/Controller/UserController.php
namespace App\Controller;
use App\DTO\UserDTO;
class UserController
{
public function showUser(User $user)
{
$userDTO = new UserDTO();
$userDTO->name = $user->getName();
$userDTO->email = $user->getEmail();
return $this->render('user.html.twig', [
'user' => $userDTO
]);
}
}
Output example
Rendered user.html.twig with user data
Code explanation
src/DTO/UserDTO.php
: This file contains the definition of the UserDTO class, which is used to store the user data.src/Controller/UserController.php
: This file contains the showUser() method, which is used to retrieve the user data from the database and store it in a UserDTO object. The UserDTO object is then passed to the view.
Helpful links
More of Php Symfony
- How to check PHP Symfony version?
- How to create a model in PHP Symfony?
- How to process async tasks in PHP Symfony?
- What are the required PHP Symfony extensions?
- How to use the messenger component in PHP Symfony?
- How to generate a model in PHP Symfony?
- How to install Symfony on Windows?
- How to use websockets in PHP Symfony?
- How to upload a file in PHP Symfony?
- How to create a backend with PHP Symfony?
See more codes...