Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/headio/phalcon-bootstrap
A flexible application bootstrap for Phalcon-based projects
https://github.com/headio/phalcon-bootstrap
api bootstrapping cli di-container modular mvc phalcon phalcon-bootstrap phalcon4 phalcon5 php7 php72 php73 php74 php8 php80
Last synced: 4 months ago
JSON representation
A flexible application bootstrap for Phalcon-based projects
- Host: GitHub
- URL: https://github.com/headio/phalcon-bootstrap
- Owner: headio
- License: mit
- Created: 2020-01-11T14:04:27.000Z (about 5 years ago)
- Default Branch: 5.x
- Last Pushed: 2022-03-02T09:06:24.000Z (almost 3 years ago)
- Last Synced: 2024-09-29T19:41:58.018Z (4 months ago)
- Topics: api, bootstrapping, cli, di-container, modular, mvc, phalcon, phalcon-bootstrap, phalcon4, phalcon5, php7, php72, php73, php74, php8, php80
- Language: PHP
- Homepage:
- Size: 171 KB
- Stars: 4
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Phalcon application bootstrap
A flexible application bootstrap for Phalcon-based projects
[![Build Status](https://travis-ci.com/headio/phalcon-bootstrap.svg?branch=5.x)](https://travis-ci.com/headio/phalcon-bootstrap) [![Coverage Status](https://coveralls.io/repos/github/headio/phalcon-bootstrap/badge.svg?branch=5.x)](https://coveralls.io/github/headio/phalcon-bootstrap?branch=5.x)
## Description
This library provides flexible application bootstrapping, encapsulating module registration (or handler registration for micro applications), event management and middleware logic assignment for mvc, micro and cli-based applications.
A simple factory instantiates the dependency injection container, encapsulating the registration of service dependency definitions defined in the configuration setttings.## Dependencies
* PHP >=8.0
* Phalcon >=5.0.0See composer.json for more details
## Installation
### Composer
Open a terminal window and run:
```bash
composer require headio/phalcon-bootstrap
```## Usage
### Micro applications (Api, prototype or micro service)
First create a config definition file inside your Phalcon project. This file should include the configuration settings, service & middleware definitions and a path to your handlers.
To get started, let's assume the following project structure:
```bash
├── public
│ ├── index.php
├── src
│ ├── Config
│ │ │── Config.php
│ │ │── Handlers.php
│ │── Controller
│ │── Domain
│ │── Middleware
│ │── Service
│ │── Var
│ │ │── Log
├── tests
├── vendor
├── Boot.php
├── codeception.yml
├── composer.json
├── .gitignore
├── README.md
└── .travis.yml
```and your PSR-4 autoload declaration is:
```json
{
"autoload": {
"psr-4": {
"Foo\\": "src/"
}
}
}
```Create a config file **Config.php** inside the **Config** directory and copy-&-paste the following definition:
```php
dirname(__DIR__) . DIRECTORY_SEPARATOR,
'debug' => true,
'locale' => 'en_GB',
'logPath' => dirname(__DIR__) .
DIRECTORY_SEPARATOR . 'Var' .
DIRECTORY_SEPARATOR . 'Log' .
DIRECTORY_SEPARATOR,
'handlerPath' => __DIR__ . DIRECTORY_SEPARATOR . 'Handlers.php',
'middleware' => [
NotFoundMiddleware::class => 'before'
],
'services' => [
'Foo\Service\EventManager',
'Foo\Service\Logger',
],
'timezone' => 'Europe\London'
];
```The **handlerPath** declaration must include your handlers; the best strategy is to utilize Phalcon collections. The contents of this file might look something like this:
```php
setHandler(Index::class, true);
$handler->setPrefix('/');
$handler->get('/', 'indexAction', 'apiIndex');
$app->mount($handler);
```Now, create an index file inside the **public** directory and copy-&-paste the following:
```php
createDefaultMvc();// Environment
if (extension_loaded('mbstring')) {
mb_internal_encoding('UTF-8');
mb_substitute_character('none');
}set_error_handler(
function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// Unmasked error context
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
}
);set_exception_handler(
function (Throwable $e) use ($di) {
$di->get('logger')->error($e->getMessage(), ['exception' => $e]);// Verbose exception handling for development
if ($di->get('config')->debug) {
}exit(1);
}
);// Run the application
return Bootstrap::handle($di)->run($_SERVER['REQUEST_URI'], Bootstrap::Micro);
})();
```### Mvc applications
Create a config definition file inside your Phalcon project. This file should include your configuration settings and service & middleware definitions.
Let's assume the following mvc project structure:
```bash
├── public
│ ├── index.php
├── src
│ ├── Config
│ │ │── Config.php
│ │── Controller
│ │── Domain
│ │── Middleware
│ │── Module
│ │ │── Admin
│ │ │ │── Controller
│ │ │ │── Form
│ │ │ │── Task
│ │ │ │── View
│ │ │ │── Module.php
│ │── Service
│ │── Var
│ │ │── Log
├── tests
├── vendor
├── Boot.php
├── codeception.yml
├── composer.json
├── .gitignore
├── README.md
└── .travis.yml
```and your PSR-4 autoload declaration is:
```json
{
"autoload": {
"psr-4": {
"Foo\\": "src/"
}
}
}
```Create a config file **Config.php** inside the **Config** directory and copy-&-paste the following definition:
```php
[
'adapter' => 'Apcu',
'options' => [
'lifetime' => 3600 * 24 * 30,
'prefix' => 'annotations',
],
],
'applicationPath' => dirname(__DIR__) . DIRECTORY_SEPARATOR,
'baseUri' => '/',
'debug' => true,
'dispatcher' => [
'defaultAction' => 'index',
'defaultController' => 'Admin',
'defaultControllerNamespace' => 'Foo\\Module\\Admin\\Controller',
'defaultModule' => 'admin'
],
'locale' => 'en_GB',
'logPath' => dirname(__DIR__) .
DIRECTORY_SEPARATOR . 'Var' .
DIRECTORY_SEPARATOR . 'Log' .
DIRECTORY_SEPARATOR,
'modules' => [
'admin' => [
'className' => 'Foo\\Module\\Admin\\Module',
'path' => dirname(__DIR__) . '/Module/Admin/Module.php'
],
],
'middleware' => [
'Foo\\Middleware\\Bar'
],
'routes' => [
'admin' => [
'Foo\Module\Admin\Controller\Admin' => '/admin',
],
],
'services' => [
'Foo\Service\EventManager',
'Foo\Service\Logger',
'Foo\Service\Annotation',
'Foo\Service\Router',
'Foo\Service\View'
],
'timezone' => 'Europe\London',
'useI18n' => true,
'view' => [
'defaultPath' => dirname(__DIR__) . '/Module/Admin/View/',
'compiledPath' => dirname(__DIR__) . '/Cache/Volt/',
'compiledSeparator' => '_',
]
];
```Now, create an index file inside the **public** directory and paste the following:
```php
createDefaultMvc();// Environment
if (extension_loaded('mbstring')) {
mb_internal_encoding('UTF-8');
mb_substitute_character('none');
}set_error_handler(
function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// Unmasked error context
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
}
);set_exception_handler(
function (Throwable $e) use ($di) {
$di->get('logger')->error($e->getMessage(), ['exception' => $e]);// Verbose exception handling for development
if ($di->get('config')->debug) {
}exit(1);
}
);// Run the application
return Bootstrap::handle($di)->run($_SERVER['REQUEST_URI']);
})();
```### Console application
Create a config definition file inside your Phalcon project. This file should include your configuration settings and service & middleware definitions.
Let's assume the following project structure:
```bash
├── src
│ ├── Config
│ │ │── Config.php
│ │── Domain
│ │── Middleware
│ │── Service
│ │── Task
│ │── Var
│ │ │── Log
├── tests
├── vendor
├── Cli.php
├── codeception.yml
├── composer.json
├── .gitignore
├── README.md
└── .travis.yml
```and your PSR-4 autoload declaration is:
```json
{
"autoload": {
"psr-4": {
"Foo\\": "src/"
}
}
}
```Create a config file **Config.php** inside the **Config** directory and copy-&-paste the following definition:
```php
dirname(__DIR__) . DIRECTORY_SEPARATOR,
'locale' => 'en_GB',
'logPath' => dirname(__DIR__) .
DIRECTORY_SEPARATOR . 'Var' .
DIRECTORY_SEPARATOR . 'Log' .
DIRECTORY_SEPARATOR,
'debug' => true,
'dispatcher' => [
'defaultTaskNamespace' => 'Foo\\Task',
],
'middleware' => [
],
'services' => [
'Foo\Service\EventManager',
'Foo\Service\Logger',
'Foo\Service\ConsoleOutput',
],
'timezone' => 'Europe\London'
];
```Finally, paste the following bootstrap code inside the **Cli.php** file:
```php
createDefaultCli();// Environment
set_error_handler(
function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// Unmasked error context
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
}
);set_exception_handler(
function (Throwable $e) use ($di) {
$di->get('logger')->error($e->getMessage(), ['exception' => $e]);
$output = $di->get('consoleOutput');
$output->writeln('' . $e->getMessage() . '');// Verbose exception handling for development
if ($di->get('config')->debug) {
$output->writeln(sprintf(
'Exception thrown in: %s at line %d.',
$e->getFile(),
$e->getLine())
);
}exit(1);
}
);// Run the application
return Bootstrap::handle($di)->run($_SERVER);
})();
```## DI container factory
From the examples above you will have noticed that we instantiated Phalcon's factory default mvc or cli container services.
```php
$config = new Config(
require __DIR__ . '/src/Config/Config.php'
);// Micro/Mvc
$di = (new DiFactory($config))->createDefaultMvc();// Cli
$di = (new DiFactory($config))->createDefaultCli();
```Naturally, you can override the factory default services by simply defining a service definition in your config file, like so:
```php
[
'Foo\Service\Router'
]
]```
Then create the respective service provider and modify its behaviour:
```php
setShared(
'router',
function () use ($di) {
$config = $di->get('config');if ($config->get('cli')) {
$service = new CliService();
$service->setDefaultModule($config->dispatcher->defaultTaskModule);
return $service;
}if (!$config->has('modules')) {
throw new OutOfRangeException('Undefined modules');
}if (!$config->has('routes')) {
throw new OutOfRangeException('Undefined routes');
}$service = new MvcService(false);
$service->removeExtraSlashes(true);
$service->setDefaultNamespace($config->dispatcher->defaultControllerNamespace);
$service->setDefaultModule($config->dispatcher->defaultModule);
$service->setDefaultController($config->dispatcher->defaultController);
$service->setDefaultAction($config->dispatcher->defaultAction);foreach ($config->get('modules')->toArray() ?? [] as $module => $settings) {
if (!$config->routes->get($module, false)) {
continue;
}
foreach ($config->get('routes')->{$module}->toArray() ?? [] as $key => $val) {
$service->addModuleResource($module, $key, $val);
}
}return $service;
}
);
}
}
```For complete control over the registration of service dependencies, or more generally, the services available in the container, you have two options: firstly, you can use Phalcon's base DI container, which is an empty container; or you can create your own DI container by implementing Phalcon's **Phalcon\Di\DiInterface**. See the following for an example:
```php
use Phalcon\Di;
use Foo\Bar\MyDi;$config = new Config(
require __DIR__ . '/src/Config/Config.php'
);// Empty DI container
$di = (new DiFactory($config))->create(new Di);// Custom DI container
$di = (new DiFactory($config))->create(new MyDi);
```The DI factory **create method** expects an instance of **Phalcon\Di\DiInterface**.
## Application factory
The bootstrap factory will automatically instantiate a Phalcon application and return the response. If you want to bootstrap the application yourself, you can use the application factory directly.
```php
createDefaultMvc();/** @var Phalcon\Mvc\Application */
$app = (new AppFactory($di))->createForMvc();// Do some stuff
/** @var Phalcon\Mvc\ResponseInterface|bool */
$response = $app->handle($_SERVER['REQUEST_URI']);if ($response instanceof \Phalcon\Mvc\ResponseInterface) {
return $response->send();
}return $response;
} catch(\Throwable $e) {
echo $e->getMessage();
}
```## Testing
To see the tests, run:
```bash
php vendor/bin/codecept run -f --coverage --coverage-text
```## License
Phalcon bootstrap is open-source and licensed under [MIT License](http://opensource.org/licenses/MIT).