PHP code example of devtools-marvellous / rest-actions

1. Go to this page and download the library: Download devtools-marvellous/rest-actions 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/ */

    

devtools-marvellous / rest-actions example snippets


    abstract class CoreController extends Controller
    {
        use RestActions;

        ...

        public function serverResponse()
        {
            return (new ServerResponse());
        }
    }

class CategoryController extends CoreController
{
    use IndexAction, ShowAction, StoreAction, UpdateAction, DestroyAction;

    protected $actions = [
        'index' => [
            'request'     => CategoryRequest::class,
            'view'        => 'backend.categories.index',
        ],
        'show'  => [
            'request'     => CategoryRequest::class,
        ],
        'store' => [
            'request' => CategoryRequest::class,
        ],
        'update' => [
            'request' => CategoryRequest::class,
            'parameters' => [
                'category' => Category::class
            ]
        ],
        'destroy' => [
            'request' => CategoryRequest::class,
        ]
    ];

    /**
     * UserController constructor.
     *
     * @param CategoryRepository $repository
     */
    public function __construct(CategoryRepository $repository)
    {
        $this->repository = $repository;
    }
}

'index'   => [
    'request'    => CourseRequest::class,
    'view'       => '',
    'ajaxTransform' => false,
    'conditions' => [
        'limit' => 20,
    ],
],

protected $modelCAlss = SubCategory::calss;

'update' => [
    'request' => CategoryRequest::class,
    'repository' => 'someOtherUpdateFunctionName'
],

'update' => [
    'request' => CategoryRequest::class,
    'parameters' => [
        'category' => Category::class // ключ массива в точности повторяет ключ из урла. Для правильности ввода воспользоваться php artisan route:list.
    ]
],

    public function update(Repository $repository, Category $category)

'update' => [
    'request' => CategoryRequest::class,
    'parameters' => [
        // ключ массива parameters в точности повторяет ключ из урла. Для правильности ввода воспользоваться php artisan route:list.
        'category' => ['class' => Category::class, 'parameter_name' => 'vocabulariable'], 
    ]
],

    public function update(Repository $repository, Vocabulariable $vocabulariable);

public function update(Repository $repository, Category $category, $someParam = false);

'update' => [
    'request' => CategoryRequest::class,
    'parameters' => [
        'category' => Category::class, // ключ в точности повторяет ключ из урла. Для правильности ввода воспользоваться php artisan route:list.
        'someParam' => true
    ]
],

'index' => [
    'request'     => CategoryRequest::class,
    'view'        => 'backend.categories.index',
],

/**
 * TODO redeclare to add default data for all views.
 *
 * @return array
 */
protected function restDefaultData()
{
    return [];
}

/**
 * Return index additional parameters to filter.
 *
 * TODO Redeclare this function in controller to make request a little bit secure for example.
 *
 * @param Request $request
 * @param Router  $router
 *
 * @return array
 */
protected function getIndexFilterParameters(Request $request, Router $router)
{
    return [
        //'parameters'  => $this->getActionConditions($router)->toArray(), - Стандартное использование, достает параметры из массива $actions.
        'parameters'  => [
            'filter' => [
                'sub_category.category_id' => 1
            ]
        ],
    ];
}

/**
 * Extend index response.
 *
 * TODO redeclare this function in controller and return extended information.
 *
 * @param Request $request
 * @param Router  $router
 *
 * @return array
 */
protected function extendIndexResponse(Request $request, Router $router)
{
    return [ ];
}

// ДЛЯ SHOW ФУНКЦИИ

/**
 * Return index additional parameters to filter.
 *
 * TODO Redeclare this function in controller to make request a little bit secure for example.
 *
 * @param Request $request
 * @param Router  $router
 *
 * @return array
 */
protected function getShowFilterParameters(Request $request, Router $router)
{
    return [
        'parameters'  => $this->getActionConditions($router)->toArray(),
    ];
}

/**
 * Extend index response.
 *
 * TODO redeclare this function in controller and return extended information.
 *
 * @param Request $request
 * @param Router  $router
 *
 * @return array
 */
protected function extendShowResponse(Request $request, Router $router)
{
    return [ ];
}

/**
 * Return route key name.
 *
 * @return string
 */
public function getRouteKeyName()
{
    return 'uri';
}

 /**
 * Return model for actions.
 *
 * TODO redeclare this function and append more secure db request if needed.
 *
 * @param $id
 *
 * @return mixed
 */
protected function getModelForActions($id, Model $model, Request $request)
{
     // Check if we receive current REST model.
    if($model->is($this->restMakeModel())){
        $query =  $this->getBaseFilterQuery($request);
    }else{
        $query = $model->newQuery();
    }

    return $query->where($model->getRouteKeyName(), $id)->firstOrFail();
}

 /**
  * Return base query builder.
  *
  * @param $actionName - name of the action from actions array.
  * @param Request $request
  *                    
  * @return \Illuminate\Database\Eloquent\Builder
  */
 protected function getBaseFilterQuery(Request $request)
 {
     return $this->restMakeModel()->newQuery();
 }

    /**
     * Return extended actions.
     *
     * @param Router $router
     *
     * @return array
     */
    public function getActions(Router $router)
    {
        $actions = parent::getActions($router); // parent - Расширяемый контроллер.

        return array_merge($actions, [
            'store' => [
                'request'     => CampaignRequest::class,
                'transformer' => CampaignResource::class,
            ],
        ]);
    }

    class UserController extends CoreController
    {
    
        use IndexAction;
    
    
        /**
         * Main request class.
         *
         * @var string
         */
        protected $restActionsRequest = UserRequest::class;
    
        /**
         * Possible actions.
         *
         * @var array
         */
        protected $actions = [
            'index'   => [
                'onlyAjax'    => true,
                'transformer' => UserResource::class,
            ],
        ];
        
        /**
         * UserController constructor.
         *
         * @param UserRepository $repository
         */
        public function __construct(UserRepository $repository)
        {
    
            $this->repository = $repository;
        }
    }
    
    class PostOwnerController extends UserController
    {
        /**
         * Main request class.
         *
         * @var string
         */
        protected $restActionsRequest = PostOwnerRequest::class;
    
    
        /**
         * PostOwnerRepository constructor.
         *
         * @param PostOwnerRepository $repository
         */
        public function __construct(PostOwnerRepository $repository)
        {
            parent::__construct($repository);
        }
    
        /**
         * Return base filter builder.
         *
         * @param $actionName
         *
         * @return \Illuminate\Database\Eloquent\Builder
         */
        protected function getBaseFilterQuery(Request $request)
        {
            return $this->repository->newQuery()->hasPermission([ Permission::CAN_OWN_POST ]);
        }
    }

'index'   => [
    'request'    => CourseRequest::class,
    'view'       => '',
    'ajaxTransform' => false,
    'conditions' => [
        'limit' => 20,
    ],
],

$response = app(CourseController::class)->index($router);

if($response instanceof Collection){
    //return response for filter and change it
    //or render spesific view with collectioned data or transform it for your self.

}

//return view
return $response;

app(CourseController::class)
    ->setActionView('index', 'frontend.filter.sub_category')
    ->setActionRepositoryMethod('index', 'newMethodName')
    ->setActionConditions('index', [ 'limit' => 20 ])
    ->setActionParameters('index', [ 'course' => SubCategory::class ])
    ->index($router);

'index'   => [
    'request'    => CourseRequest::class,
    'cache' => [
        'time' => 120, // in secs
        'tags' => 'courses_list' // tag is not available on all cache drivers, but always 

[
    'request' => Request::class,
    'model' => null, 
    'view' => null,
    'conditions' => [],
    'transformer' => Resource::class,
    'ajaxTransform' => true,
    'simpleView' => false,
    'onlyAjax' => false,
    'onlyBrowser' => false,
    'cache' => [
        'time' => false,
        'tag' => null
    ],
    'protectedLimit' => self::$PROTECTED_LIMIT,
    
]