PHP code example of jarischaefer / hal-api

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

    

jarischaefer / hal-api example snippets


'providers' => [
	Jarischaefer\HalApi\Providers\HalApiServiceProvider::class,
]

'providers' => [
	Jarischaefer\HalApi\Providers\HalApiServiceProvider::class,
]

class HomeController extends HalApiController
{

	public function index(HalApiRequestParameters $parameters)
	{
		return $this->responseFactory->json($this->createResponse($parameters)->build());
	}

}

class UsersController extends HalApiResourceController
{

	public static function getRelationName(): string
	{
		return 'users';
	}

	public function __construct(HalApiControllerParameters $parameters, UserTransformer $transformer, UserRepository $repository)
	{
		parent::__construct($parameters, $transformer, $repository);
	}

	public function posts(HalApiRequestParameters $parameters, PostsController $postsController, User $user): Response
	{
		$posts = $user->posts()->paginate($parameters->getPerPage());
		$response = $postsController->paginate($parameters, $posts)->build();

		return $this->responseFactory->json($response);
	}

}

class PostsController extends HalApiResourceController
{

	public static function getRelationName(): string
	{
		return 'posts';
	}

	public function __construct(HalApiControllerParameters $parameters, PostTransformer $transformer, PostRepository $repository)
	{
		parent::__construct($parameters, $transformer, $repository);
	}

}

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{

	use Authenticatable, CanResetPassword;

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token'];

	public function posts()
	{
		return $this->hasMany(Post::class);
	}

}

class Post extends Model
{

	// ...

	public function user()
	{
		return $this->belongsTo(User::class);
	}

}

class UserRepository extends HalApiEloquentRepository
{

	public static function getModelClass(): string
	{
		return User::class;
	}

}

class PostRepository extends HalApiEloquentRepository
{

	public static function getModelClass(): string
	{
		return Post::class;
	}

}

class UserRepository extends HalApiEloquentSearchRepository
{

	public static function getModelClass(): string
	{
		return User::class;
	}

	public static function searchableFields(): array
	{
		return [User::COLUMN_NAME];
	}

}

class PostRepository extends HalApiEloquentSearchRepository
{

	public static function getModelClass(): string
	{
		return Post::class;
	}

	public static function searchableFields(): array
	{
		return ['*'];
	}

}

class UserTransformer extends HalApiTransformer
{

	public function transform(Model $model)
	{
		/** @var User $model */

		return [
			'id' => (int)$model->id,
			'username' => (string)$model->username,
			'email' => (string)$model->email,
			'firstname' => (string)$model->firstname,
			'lastname' => (string)$model->lastname,
			'disabled' => (bool)$model->disabled,
		];
	}

}

class PostTransformer extends HalApiTransformer
{

	public function transform(Model $model)
	{
		/** @var Post $model */

		return [
			'id' => (int)$model->id,
			'title' => (string)$model->title,
			'text' => (string)$model->text,
			'user_id' => (int)$model->user_id,
		];
	}

}

class PostTransformer extends HalApiTransformer
{

	private $userRoute;

	private $userRelation;

	public function __construct(LinkFactory $linkFactory, RepresentationFactory $representationFactory, RouteHelper $routeHelper, Route $self, Route $parent)
	{
		parent::__construct($linkFactory, $representationFactory, $routeHelper, $self, $parent);

		$this->userRoute = $routeHelper->byAction(UsersController::actionName(RouteHelper::SHOW));
		$this->userRelation = UsersController::getRelation(RouteHelper::SHOW);
	}

	public function transform(Model $model)
	{
		/** @var Post $model */

		return [
			'id' => (int)$model->id,
			'title' => (string)$model->title,
			'text' => (string)$model->text,
			'user_id' => (int)$model->user_id,
		];
	}

	protected function getLinks(Model $model)
	{
		/** @var Post $model */

		return [
			$this->userRelation => $this->linkFactory->create($this->userRoute, $model->user_id),
		];
	}

}

class PostTransformer extends HalApiTransformer
{

	private $userTransformer;

	private $userRelation;

	public function __construct(LinkFactory $linkFactory, RepresentationFactory $representationFactory, RouteHelper $routeHelper, Route $self, Route $parent, UserTransformer $userTransformer)
	{
		parent::__construct($linkFactory, $representationFactory, $routeHelper, $self, $parent);

		$this->userTransformer = $userTransformer;
		$this->userRelation = UsersController::getRelation(RouteHelper::SHOW);
	}

	public function transform(Model $model)
	{
		/** @var Post $model */

		return [
			'id' => (int)$model->id,
			'title' => (string)$model->title,
			'text' => (string)$model->text,
			'user_id' => (int)$model->user_id,
		];
	}

	protected function getEmbedded(Model $model)
	{
		/** @var Post $model */

		return [
			$this->userRelation => $this->userTransformer->item($model->user),
		];
	}

}

class MyServiceProvider extends ServiceProvider
{

	public function boot(Router $router)
	{
		$this->app->singleton(UserTransformer::class, function (Illuminate\Contracts\Foundation\Application $application) {
			$linkFactory = $application->make(LinkFactory::class);
			$representationFactory = $application->make(RepresentationFactory::class);
			$routeHelper = $application->make(RouteHelper::class);
			$self = $routeHelper->byAction(UsersController::actionName(RouteHelper::SHOW));
			$parent = $routeHelper->parent($self);

			return new UserTransformer($linkFactory, $representationFactory, $routeHelper, $self, $parent);
		});

		$this->app->singleton(PostTransformer::class, function (Illuminate\Contracts\Foundation\Application $application) {
			$linkFactory = $application->make(LinkFactory::class);
			$representationFactory = $application->make(RepresentationFactory::class);
			$routeHelper = $application->make(RouteHelper::class);
			$self = $routeHelper->byAction(PostsController::actionName(RouteHelper::SHOW));
			$parent = $routeHelper->parent($self);
			$userTransformer = $application->make(UserTransformer::class);

			return new PostTransformer($linkFactory, $representationFactory, $routeHelper, $self, $parent, $userTransformer);
		});
	}

}

RouteHelper::make($router)
	->get('/', HomeController::class, 'index') // Link GET / to the index method in HomeController

	->resource('users', UsersController::class) // Start a new resource block
		->get('posts', 'posts') // Link GET /users/{users}/posts to the posts method in UsersController
	->done() // Close the resource block

	->resource('posts', PostsController::class)
	->done();

RouteHelper::make($router)
	->resource('users', UsersController::class, [RouteHelper::SHOW, RouteHelper::INDEX], false)
	->done();

RouteHelper::make($router)
	->resource('users', UsersController::class)
		->searchable()
	->done();

public function boot(Router $router)
{
	parent::boot($router);

	$callback = RouteHelper::getModelBindingCallback();
	$router->model('users', User::class, $callback);
	$router->model('posts', Post::class, $callback);
}

class Handler extends ExceptionHandler
{

	public function report(Exception $e)
	{
		parent::report($e);
	}

	public function render($request, Exception $e)
	{
		switch (get_class($e)) {
			case ModelNotFoundException::class:
				return response('', Response::HTTP_NOT_FOUND);
			case NotFoundHttpException::class:
				return response('', Response::HTTP_NOT_FOUND);
			case BadPutRequestException::class:
				return response('', Response::HTTP_UNPROCESSABLE_ENTITY);
			case BadPostRequestException::class:
				return response('', Response::HTTP_UNPROCESSABLE_ENTITY);
			case TokenMismatchException::class:
				return response('', Response::HTTP_FORBIDDEN);
			case DatabaseConflictException::class:
				return response('', Response::HTTP_CONFLICT);
			case DatabaseSaveException::class:
				$this->report($e);
				return response('', Response::HTTP_UNPROCESSABLE_ENTITY);
			case FieldNotSearchableException::class:
			    return response('', Response::HTTP_FORBIDDEN);
			default:
				$this->report($e);

				return Config::get('app.debug') ? parent::render($request, $e) : response('', Response::HTTP_INTERNAL_SERVER_ERROR);
		}
	}

}