PHP code example of mcustiel / 104

1. Go to this page and download the library: Download mcustiel/104 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mcustiel / 104 example snippets



// UserController.php
class UsersController extends Controller
{
    /** @var QueryBus */
    private $queryBus;
    
    public function __construct(QueryBus $queryBus)
    {
        $this->queryBus = $queryBus;
    }
    
    /**
     * @Route("/user/{id}", name="user_data", methods={"GET"})
     */
    public function getUserData($id): Response
    {
        try {
            $userId = new UserId($id);
            $result = $this->queryBus->dispatch(new GetUserDataQuery($userId));

            if ($result->isPresent()) {
                $user = $result->getResult();
                $userSettings = $user->getSettings();

                return new JsonResponse($user);
            }

            return new JsonREsponse(
                ['message' => 'error.userNotFound'],
                JsonResponse::HTTP_NOT_FOUND
            );
        } catch (\Exception $e) {
            return new JsonResponse(
                ['message' => 'error.unexpected ' . $e->__toString()],
                JsonResponse::HTTP_INTERNAL_SERVER_ERROR
            );
        }
    }


// GetUserDataQuery.php

class GetUserDataQuery implements Query
{
    /** @var UserId */
    private $userId;

    public function __construct(UserId $userId)
    {
        $this->userId = $userId;
    }

    public function getUserId(): UserId
    {
        return $this->userId;
    }

    public function getQueryHandler(): HandlerIdentifier
    {
        // The identifier is a string with the key of the object in the container.
        return new HandlerIdentifier(GetUserDataQueryHandler::class);
    }
}


// GetUserDataQueryHandler.php
class GetUserDataQueryHandler implements QueryHandler
{    
    /** @var UserRepository */
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function handle(Query $query): OptionalResult
    {
        // Do all the magic needed to get the user from repository here
        return new GetUserDataQueryOptionalResult($user);
    }
}


// GetUserDataQueryOptionalResult.php
class GetUserDataQueryOptionalResult extends OptionalResult
{
    public function __construct(?User $result = null)
    {
        parent::__construct($result);
    }

    public function getResult(): User
    {
        return parent::getResult();
    }
}