lisi4ok/phalcon-bootstrap

这是一个用于Phalcon PHP框架的示例引导应用程序

dev-main 2022-10-11 14:33 UTC

This package is auto-updated.

Last update: 2024-09-11 18:39:49 UTC


README

Phalcon Bootstrap应用程序库

入门

要求

要在您的机器上运行此应用程序,您至少需要以下内容

安装

composer require lisi4ok/phalcon-bootstrap

许可证

Phalcon API是开源软件,许可证为MIT许可证。©

  • Zaio Klepoyshkov (lisi4ok)
  • Phalcon团队
  • 贡献者

使用

微应用程序(API、原型或微服务)

首先在您的Phalcon项目中创建一个配置定义文件。此文件应包括配置设置、服务 & 中间件定义以及到您的处理器的路径。

为了开始,让我们假设以下项目结构

├── public
│   ├── index.php
├── src
│   ├── config
│   │    │── config.php
│   │    │── handlers.php
│   │── Controllers
│   │── Domain
│   │── Middleware
│   │── Service
│   │── var
│   │    │── log
├── tests
├── vendor
├── Boot.php
├── composer.json
├── .gitignore
├── README.md

并且您的PSR-4自动加载声明是

{
    "autoload": {
        "psr-4": {
            "Foo\\": "src/"
        }
    }
}

在Config目录中创建一个名为config.php的配置文件,并将以下定义复制并粘贴进去

<?php

use Foo\Middleware\NotFoundMiddleware;

return [
    'applicationPath' => 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',
];

handlerPath声明必须包含您的处理器;最佳策略是利用Phalcon集合。此文件的内容可能如下所示

<?php

use Foo\Controllers\Index;
use Phalcon\Mvc\Micro\Collection;

$handler = new Collection();
$handler->setHandler(Index::class, true);
$handler->setPrefix('/');
$handler->get('/', 'indexAction', 'apiIndex');
$app->mount($handler);

现在,在public目录中创建一个索引文件,并将以下内容复制并粘贴进去

<?php
declare(strict_types=1);

chdir(dirname(__DIR__));
require 'Boot.php';

最后,将以下引导代码粘贴到Boot.php文件中

<?php
declare(strict_types=1);

use Phalcon\Bootstrap\Bootstrap;
use Phalcon\Bootstrap\Di\Factory as DiFactory;
use Phalcon\Bootstrap\Enumerations\Application;
use Phalcon\Config\Config;

require_once __DIR__ . '/vendor/autoload.php';

(function () {
    $config = new Config(
        require __DIR__ . '/src/config/config.php'
    );

    $di = (new DiFactory($config))->createDefaultMvc();

    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)) {
                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);
        }
    );

    return Bootstrap::handle($di)->run($_SERVER['REQUEST_URI'], Application::Micro);
})();

MVC应用程序

在您的Phalcon项目中创建一个配置定义文件。此文件应包括您的配置设置和服务 & 中间件定义。

假设以下MVC项目结构

├── public
│   ├── index.php
├── src
│   ├── config
│   │    │── config.php
│   │── Controllers
│   │── Domain
│   │── Middleware
│   │── Module
│   │    │── Admin
│   │    │    │── Controllers
│   │    │    │── Form
│   │    │    │── Task
│   │    │    │── View
│   │    │    │── Module.php
│   │── Service
│   │── var
│   │    │── log
├── tests
├── vendor
├── Boot.php
├── composer.json
├── .gitignore
├── README.md

并且您的PSR-4自动加载声明是

{
    "autoload": {
        "psr-4": {
            "Foo\\": "src/"
        }
    }
}

在Config目录中创建一个名为config.php的配置文件,并将以下定义复制并粘贴进去

<?php

return [
    'annotations' => [
        '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' => '_',
    ]
];

现在,在public目录中创建一个索引文件,并将以下内容粘贴进去

<?php
declare(strict_types=1);

chdir(dirname(__DIR__));
require 'Boot.php';

最后,将以下引导代码粘贴到Boot.php文件中

<?php
declare(strict_types=1);

use Phalcon\Bootstrap\Bootstrap;
use Phalcon\Bootstrap\Di\Factory as DiFactory;
use Phalcon\Bootstrap\Enumerations\Application;
use Phalcon\Config\Config;

require_once __DIR__ . '/vendor/autoload.php';

(function () {
    $config = new Config(
        require __DIR__ . '/src/config/config.php'
    );

    $di = (new DiFactory($config))->createDefaultMvc();

    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)) {
                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);
        }
    );

    return Bootstrap::handle($di)->run($_SERVER['REQUEST_URI'], Application::application);
})();

控制台应用程序

在您的Phalcon项目中创建一个配置定义文件。此文件应包括您的配置设置和服务 & 中间件定义。

假设以下项目结构

├── src
│   ├── config
│   │    │── config.php
│   │── Domain
│   │── Middleware
│   │── Service
│   │── Task
│   │── var
│   │    │── log
├── tests
├── vendor
├── Cli.php
├── composer.json
├── .gitignore
├── README.md

并且您的PSR-4自动加载声明是

{
    "autoload": {
        "psr-4": {
            "Foo\\": "src/"
        }
    }
}

在Config目录中创建一个名为Config.php的配置文件,并将以下定义复制并粘贴进去

<?php

return [
    'applicationPath' => 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',
];

最后,将以下引导代码粘贴到Cli.php文件中

<?php
declare(strict_types=1);

use Phalcon\Bootstrap\Cli\Bootstrap;
use Phalcon\Bootstrap\Di\Factory as DiFactory;
use Phalcon\Bootstrap\Enumerations\Application;
use Phalcon\Config\Config;

require_once __DIR__ . '/vendor/autoload.php';

(function () {
    $config = new Config(
        require __DIR__ . '/src/config/config.php'
    );

    $di = (new DiFactory($config))->createDefaultCli();

    set_error_handler(
        function ($severity, $message, $file, $line) {
            if (!(error_reporting() & $severity)) {
                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('<error>' . $e->getMessage() . '</error>');

            if ($di->get('config')->debug) {
                $output->writeln(sprintf(
                    '<error>Exception thrown in: %s at line %d.</error>',
                    $e->getFile(),
                    $e->getLine())
                );
            }

            exit(1);
        }
    );

    return Bootstrap::handle($di)->run($_SERVER, Application::Cli);
})();

DI容器工厂

从上面的示例中,您会注意到我们实例化了Phalcon的工厂默认MVC或CLI容器服务。

$config = new Config(
    require __DIR__ . '/src/config/config.php'
);

// Micro/Mvc
$di = (new DiFactory($config))->createDefaultMvc();

// Cli
$di = (new DiFactory($config))->createDefaultCli();

当然,您可以通过在配置文件中定义服务定义来覆盖工厂默认服务

<?php
namespace Foo\Config

return [
    'services' => [
        'Foo\Service\Router',
    ]
]

然后创建相应的服务提供者并修改其行为

<?php
declare(strict_types=1);

namespace Foo\Service;

use Foo\Exception\OutOfRangeException;
use Phalcon\Config\Config;
use Phalcon\Di\ServiceProviderInterface;
use Phalcon\Di\DiInterface;
use Phalcon\Cli\Router as CliService;
use Phalcon\Mvc\Router as MvcRouter;
use Phalcon\Mvc\Router\Annotations as MvcService;

class Router implements ServiceProviderInterface
{
    /**
     * {@inheritDoc}
     */
    public function register(DiInterface $di) : void
    {
        $di->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;
            }
        );
    }
}

为了完全控制服务依赖项的注册,或者更普遍地,容器中的服务,您有两个选项:首先,您可以使用Phalcon的基本DI容器,它是一个空容器;或者您可以通过实现Phalcon的Phalcon\Di\DiInterface来创建自己的DI容器。以下是一个示例

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);

DI工厂的create方法期望一个Phalcon\Di\DiInterface的实例。

应用程序工厂

引导工厂将自动实例化一个Phalcon应用程序并返回响应。如果您想自己引导应用程序,可以直接使用应用程序工厂。