跳至主要内容
版本:5.1

示例 PHP 脚本

开发者注意

创建直接包含加载和启动 CMS 框架的脚本是不推荐的,只有在极少数情况下才需要。根据用例,您应该创建 控制台插件 并扩展 Joomla! 控制台应用程序。如果您需要为 Web 请求创建一个简单的入口点,请编写一个 Ajax 插件.

通用方法

要使用 Joomla 框架,特别是 Joomla API,您需要有一个 Application 类实例。由于 ConsoleApplicationCliApplication 都有检查以确保其应用程序是从命令行运行的,并且 AdministratorApplicationApiApplication 都不合适,因此明确的选择是在 SiteApplication 上构建您的脚本。

因此,要构建您的脚本,您基本上必须镜像 Joomla 如何初始化和实例化 SiteApplication,这包括

  • 运行 Joomla 启动 PHP 文件
  • 通过依赖注入容器实例化 SiteApplication(这也将实例化其关键依赖项)
  • Application 类实例提供任何必要的配置项(例如,要使用的语言、用户、日志记录)。

由于 Joomla 启动程序会不时发生变化,您当然需要检查您的自定义脚本是否在 Joomla 的新版本上运行,并且您可能需要更改它们。

下面的代码是用于基本自定义脚本的,如果您想尝试运行它,您应该将它存储在 Joomla 实例根目录下的 /cli 目录中。您可以注释掉所有可选部分,并确认它仍然可以正常工作。

<?php

use Joomla\CMS\Factory;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Language\Language;
use Joomla\CMS\Log\Log;

define('_JEXEC', 1);

// define your preferred error reporting levels
error_reporting(E_ALL);
ini_set('display_errors', 1);

// the line below assumes that this PHP script file is in a directory below the root of the joomla instance, eg in <root>/cli
define('JPATH_BASE', realpath(dirname(__FILE__).'/..'));

require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';

// Boot the DI container - this will load in the classes in libraries/src/Service/Provider/
$container = \Joomla\CMS\Factory::getContainer();

// We need to set up an alias to get the Session dependency from the DIC
$container->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');

// Instantiate the application.
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);

// Set what gets returned from Factory::getApplication()
\Joomla\CMS\Factory::$application = $app;

// Optional - This is so that Joomla can find classes relating to extensions
$app->createExtensionNamespaceMap();

// Optional - Set up basic logging framework
if ($app->get('log_everything')) {
Log::addLogger(['text_file' => 'everything.php']);
}
Log::add('logging initialised ok', Log::DEBUG, 'script-debug');

// Optional - set up the language and load the joomla library text strings - select your preferred language
$lang = Language::getInstance("en-GB");
$app->loadLanguage($lang);
$app->getLanguage()->load('lib_joomla', JPATH_ADMINISTRATOR);

// Write below here what you want your script to do
$db = $container->get(Joomla\Database\DatabaseInterface::class);

$query = $db->getQuery(true);
$query->select('count(*)')
->from('#__content');

$db->setQuery($query);

$count = $db->loadResult();

echo "<h2>{$count} articles found</h2>";