PHP code example of larapie / guard

1. Go to this page and download the library: Download larapie/guard 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/ */

    

larapie / guard example snippets


public function foo()
{
    if($user==null)
        throw new UserNotFoundException();
        
    if($user->age < 18)
        throw new NotOldEnoughException(18);
        
    ...
}

public function foo()
{
    guard(new UserDoesNotExistsGuard($user), new UserInsufficientAgeGuard($user, 18));
}

class UserDoesNotExistsGuard extends Guard
{

    /**
     * The exception that will be thrown when the condition is met
     *
     * @var string
     */
    protected $exception = UserNotFoundException::class;


    /**
     * @var User
     */
    protected $user;

    /**
     * UserDoesNotExistsGuard constructor.
     * @param $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * The condition that needs to be satisfied in order to throw the exception.
     *
     * @return bool
     */
    public function condition(): bool
    {
        return $this->user===null;
    }
}

class UserInsufficientAgeGuard extends Guard
{
    /**
     * @var User
     */
    protected $user;
    
    /**
     * @var int
     */
    protected $age;    

    /**
     * UserDoesNotExistsGuard constructor.
     * @param $user
     */
    public function __construct(User $user, int $age)
    {
        $this->user = $user;
        $this->age = $age;
    }

    /**
     * The condition that needs to be satisfied in order to throw the exception.
     *
     * @return bool
     */
    public function condition(): bool
    {
        return $this->user->age < this->age;
    }
    
    /**
     * The exception that gets thrown when the condition is satisfied.
     *
     * @return \Throwable
     */
    public function exception(): \Throwable
    {
        return new NotOldEnoughException(18);
    }    
}