Хорошо, это немного сложно, так что несите меня.
Я запускаю PHPBB Forum в течение некоторого времени, и моя цель - создать PHP-приложение Zend2 с использованием его функций управления пользователями и аутентификации вместо создания совершенно нового компонента авторизации, который, в свою очередь, должен синхронизироваться с форумом еще раз.
Следующие компоненты будут использоваться в живой среде: PHPBB3, Zend Framework 2 (последняя стабильная версия), Apache, PHP 5.6+, MySQL, работающая на виртуальном сервере Linux без доступа root.
Моя среда разработки (все приведенные ниже примеры): PHPBB3, Zend Framework 2 (последняя стабильная версия), XAMPP 3.2.2, PHP 5.6.21 с включенным xdebug, MariaDB, работающим в Windows 8.
Всякий раз, когда требуется интегрировать PHPBB, следующие строки неизбежно появляются в результатах поиска:
global $phpbb_root_path, $phpEx, $user, $db, $config, $cache, $template;
define('IN_PHPBB', true);
$phpbb_root_path = './forum/phpBB3/'; // this path is from an external example
$phpEx = substr(strrchr(__FILE__, '.'), 1);
$phpBBFile = $phpbb_root_path . 'common.' . $phpEx;
include($phpBBFile);
// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();
У меня уже был успех, в том числе без использования фреймворка или путем прямого вызова php через ajax, но теперь - с использованием Zend 2 Framework - при включении собственного кода PHPBB3 возникает множество проблем.
Я должен сказать, что я не опытный PHP-программист, и я узнал о Zend всего пару дней.
Моя первая попытка была сосредоточена на интеграции вышеуказанного кода до того, как приложение Zend вызывается в Zends index.php
:
....
// Setup autoloading
require 'init_autoloader.php';
global $phpbb_root_path, $phpEx, $user, $db, $config, $cache, $template;
define('IN_PHPBB', true);
$phpbb_root_path = 'public/forums/';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
$phpBBFile = $phpbb_root_path . 'common.' . $phpEx;
include($phpBBFile);
// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
....
Результат этой ошибки:
Допустимая фатальная ошибка: аргумент 1 передан в Zend\Stdlib\Parameters:: __ construct() должен быть из массива типов, объект, вызываемый в C:\xampp\htdocs\myZendApp\vendor\zendframework\zend-http\src\PhpEnvironment\Request.php в строке 72 и определен в C:\xampp\htdocs\myZendApp\vendor\zendframework\zend-stdlib\src\Parameters.php в строке 24
Таким образом, вызов PHPBB на ранней стадии, похоже, испортил Zend в плохом ключе, я перешел к другим реализациям.
Мой предпочтительный дизайн будет включать отдельный модуль аутентификации Zend, который обрабатывает аутентификацию PHPBB и доступен как услуга для всех маршрутов и их контроллеров. Включение и вызов сценариев phpbb, однако, приводит к различным проблемам, вероятно, связанным с интенсивным использованием глобальных переменных.
Вот пример кода из checkAction
в PhpbbAuthController
:
public function checkAction(){
global $phpbb_root_path, $phpEx, $user, $db, $config, $cache, $template;
define('IN_PHPBB', true);
$phpbb_root_path = 'public/forums/';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
$phpBBFile = $phpbb_root_path . 'common.' . $phpEx;
include($phpBBFile);
$user->session_begin();
$auth->acl($user->data);
$user->setup();
$response = array();
if ($user->data['user_id'] == ANONYMOUS) {
$response['loginState'] = "logged_out";
} else {
$response['loginState'] = "logged_in";
}
return new ViewModel($response);
}
И здесь ошибка при выполнении session_begin()
Неустранимая ошибка: вызовите заголовок функции-члена() в нуле C:\xampp\htdocs\myZendApp\public\forums\phpbb\session.php в строке 228
После отладки в нее казалось, что все ссылки на $request и $symfony_request внутри этих функций аутентификации, где NULL.
После того, как мы потратили много времени на то, чтобы выполнить сценарии из контекста Zend, я поставил глаза на способ выполнения сценариев в отдельном контексте.
Самый простой способ, который пришел мне на ум, состоял в том, чтобы вызвать script из HttpClient
и использовать текст Result для управления моей службой аутентификации.
Для этого мне нужно будет извлечь куки файл сеанса из вызываемых скриптов и сохранить его для использования в приложении Zend.
Если я направляю скрипты через Zend Framework, я, похоже, снова сталкиваюсь с той же проблемой (с кодом PHBB в контроллере Zend), поэтому я не могу использовать маршрутизацию Zends для доступа к ним. Поскольку я использую http-запрос, я должен хранить сценарии в общедоступном каталоге или в его подкаталоге.
И вот где я сейчас. Внутренний вызов файлов php, использующих PHPBB, отлично работает сам по себе, но HttpClient
, который я использую (из класса Zend Controller на данный момент), запускает тайм-аут на каждом шагу, который я сформулировал в другом вопросе здесь: Задержка запроса клиента Zend 2 Http при запросе php файла из локального/общедоступного каталога.
Я был бы признателен за ваши взгляды, подсказки и возможные архитектуры или даже частичное решение моих проблем, упомянутых выше.
То, что я не хочу делать ни при каких обстоятельствах, - это изобретать мою собственную аутентификацию и администрирование пользователей, поскольку она всегда будет уступать сложной, но проверенной системе, которая уже находится в PHPBB, и в конечном итоге приводит к проблемам безопасности. Кроме того, приложение Zend считается "Extra", так как Форум является ядром сайта, так как сейчас ситуация стоит.
Большое спасибо за ваше время и, пожалуйста, запросите дополнительную информацию. (Я не мог включить весь код, и я не знаю, что еще будет иметь для вас отношение в данный момент)