https://github.com/basilfx/phalcon-httpcode
Add exceptions to simplify controller actions within the Phalcon Framework.
https://github.com/basilfx/phalcon-httpcode
Last synced: about 1 month ago
JSON representation
Add exceptions to simplify controller actions within the Phalcon Framework.
- Host: GitHub
- URL: https://github.com/basilfx/phalcon-httpcode
- Owner: basilfx
- License: mit
- Created: 2017-03-13T07:41:15.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-03-13T08:48:05.000Z (over 9 years ago)
- Last Synced: 2025-03-03T14:47:57.578Z (over 1 year ago)
- Language: PHP
- Size: 10.7 KB
- Stars: 0
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Phalcon-HttpCode
Add exceptions to simplify controller actions within the Phalcon Framework.
## Introduction
The inspiration for this library comes from the Django Framework, where one can throw exceptions to return a certain HTTP response.
```python
def view(request):
try:
model = Model.objects.get(pk=1)
except Model.DoesNotExist:
raise Http404("Model not found.")
# Perform action.
# ...
```
Within the Phalcon Framework, you could accomplish the same:
```php
response->setStatusCode(404);
return "Model not found.";
}
// Perform action.
// ...
}
}
```
However, this becomes cumbersome when multiple actions perform the same lookup steps and return the same response. You could improve this by refeactoring the lookup to a private method, but you still need to check its return value to determine the next action.
Exceptions will propagate, which will simplify the actions.
```php
getModel();
// Perform action.
// ...
}
}
```
## Requirements
* PHP 7.0 or later.
* Phalcon Framework 3.0 or later.
## Installation
Install this dependency using `composer require basilfx/phalcon-httpcode`.
In your dependency injection setup, register the dispatcher. The dispatcher will re-throw any HttpCode exception. You can catch the `dispatch:beforeHttpCode` event to handle it your own way. You can also extend any status code and provide a `toResponse($response)` method to provide the result.
```php
set("dispatcher", function () use ($di) {
$dispatcher = new Dispatcher();
$eventsManager = $di->getShared("eventsManager");
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}, true);
```
You can still catch other exceptions using the `dispatcher:beforeException` event, but make sure you pass HttpCode exceptions.
```php