Как включить модуль Phalcon встроенный в ServBay
Как мощный интегрированный инструмент для веб-разработки, ServBay поставляется с модулем Phalcon, и его активация очень проста. Phalcon, как высокопроизводительный PHP-фреймворк, благодаря своей модульной архитектуре позволяет разработчикам легко создавать эффективные веб-приложения.
Введение в Phalcon
Phalcon - это полнофункциональный PHP-фреймворк с открытым исходным кодом, известный своей скоростью и низким потреблением ресурсов. В отличие от традиционных PHP-фреймворков, Phalcon написан на языке C и загружается как расширение PHP. Это дает Phalcon значительные преимущества в производительности, а также предоставляет богатый набор функций.
Основные особенности
- Высокая производительность: Поскольку Phalcon работает как расширение на C, он быстрее фреймворков, реализованных исключительно на PHP, и потребляет меньше ресурсов.
- Низкие накладные расходы: Архитектура Phalcon разработана так, чтобы занимать меньше памяти и ресурсов ЦПУ при обработке запросов.
- Богатые функции: Phalcon предоставляет полный MVC-структуру, ORM, шаблонный движок, маршрутизацию, кеширование, очереди и другие функции, удовлетворяющие различным потребностям веб-разработки.
- Простота использования: Несмотря на то, что Phalcon написан на C, разработчики могут использовать знакомый синтаксис PHP, что снижает порог вхождения.
- Модульная архитектура: Компоненты Phalcon строго модульные, что позволяет разработчикам выбирать и использовать различные компоненты по мере необходимости.
Версии модуля Phalcon в ServBay
ServBay поддерживает несколько версий PHP, и для каждой версии предварительно установлен соответствующий модуль Phalcon. Конкретные версии следующие:
- PHP 5.6, 7.0, 7.1: Phalcon 3.4.5
- PHP 7.2, 7.3, 7.4: Phalcon 4.1.2
- PHP 8.0, 8.1, 8.2, 8.3, 8.4: Phalcon 5.7.0
Как включить модуль Phalcon
По умолчанию модуль Phalcon отключен. Процесс активации модуля Phalcon очень прост и требует только изменения конфигурационного файла для соответствующей версии PHP. Вот подробные шаги:
Шаг 1: Найти конфигурационный файл
Сначала найдите каталог conf.d
для соответствующей версии PHP. Например, чтобы включить модуль Phalcon для PHP 8.3, отредактируйте следующий файл:
/Applications/ServBay/etc/php/8.3/conf.d/phalcon.ini
Шаг 2: Редактировать конфигурационный файл
Открыть файл phalcon.ini
и раскомментируйте следующую строку:
[Phalcon]
; Uncomment the following line to enable Phalcon
extension = phalcon.so
2
3
Шаг 3: Включите модуль PSR (только для версий PHP 7.2 - PHP 7.4)
Для версий PHP 7.2 до PHP 7.4 необходимо дополнительно загрузить модуль PSR (ServBay уже содержит его):
; Uncomment both Psr & Phalcon to enable Phalcon
[Psr]
extension = psr.so
[Phalcon]
extension = phalcon.so
2
3
4
5
Шаг 4: Перезапустите PHP сервис
В панели управления сервисами ServBay перезапустите соответствующий PHP сервис. Например, перезапустите сервис PHP 8.3. После перезапуска модуль Phalcon будет успешно загружен.
Проверка успешной загрузки модуля Phalcon
Можно создать простой PHP файл для проверки, успешно ли загружен модуль Phalcon. Создайте файл phpinfo.php
в корневом каталоге веб-сервера со следующим содержимым:
<?php
phpinfo();
?>
2
3
Затем перейдите по адресу https://servbay.host/phpinfo.php
и проверьте вывод страницы информации о PHP на наличие информации о модуле Phalcon. Если модуль Phalcon присутствует, это означает, что он успешно загружен.
Пример использования
После активации модуля Phalcon можно использовать Phalcon фреймворк в PHP-коде для создания веб-приложений. Вот простой пример, демонстрирующий создание базового веб-приложения с использованием Phalcon:
Пример кода
- Создание структуры проекта
phalcon
├── app
│ ├── controllers
│ │ └── IndexController.php
│ └── views
│ └── index
│ └── index.phtml
└── public
└── index.php
2
3
4
5
6
7
8
9
- Фронт-контроллер: public/index.php
<?php
use Phalcon\Autoload\Loader;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url;
use Phalcon\Mvc\Application;
define('BASE_PATH', dirname(__DIR__ . '/../../'));
define('APP_PATH', BASE_PATH . '/app');
$loader = new Loader();
$loader->setDirectories(
[
APP_PATH . '/controllers/',
APP_PATH . '/models/',
]
);
$loader->register();
$container = new FactoryDefault();
$container->set(
'view',
function () {
$view = new View();
$view->setViewsDir(APP_PATH . '/views/');
return $view;
}
);
$container->set(
'url',
function () {
$url = new Url();
$url->setBaseUri('/');
return $url;
}
);
$application = new Application($container);
try {
// Handle the request
$response = $application->handle(
$_SERVER["REQUEST_URI"]
);
$response->send();
} catch (\Exception $e) {
echo 'Exception: ', $e->getMessage();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
- Контроллер: app/controllers/IndexController.php
<?php
use Phalcon\Mvc\Controller;
use Phalcon\Support\Version;
class IndexController extends Controller
{
public function indexAction()
{
// Получение версии Phalcon
$phalconVersion = new Version();
// Передача версии во представление
$this->view->phalconVersion = $phalconVersion->get();
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- Вид: app/views/index/index.phtml
<!DOCTYPE html>
<html>
<head>
<title>Hello ServBay</title>
</head>
<body>
<h1>Hello ServBay!</h1>
<p>Phalcon Version: <?= $phalconVersion ?></p>
</body>
</html>
2
3
4
5
6
7
8
9
10
Заключение
ServBay предоставляет удобный способ управления и включения модуля Phalcon. Через простую настройку и перезапуск операции разработчики могут быстро включить модуль Phalcon для разных версий PHP, чтобы полностью использовать его высокую производительность и богатый функционал, повышая эффективность разработки веб-приложений. Высокая производительность, низкие накладные расходы и богатый функционал делают Phalcon отличным выбором для создания масштабируемых и эффективных веб-приложений.