如何从外部PHP文件运行Drupal 8函数

问题描述 投票:0回答:3

有没有办法从外部PHP文件执行Drupal 8函数。

drupal drupal-8
3个回答
1
投票

如果你有Drush,你可以运行“drush scr [filename]”来执行文件以及bootstrap Drupal。我做了一篇关于此的博客文章 - https://www.oliverdavi.es/blog/dont-bootstrap-drupal-use-drush

我只将它用于简单的本地测试脚本,但在将代码移动到适当的函数/类/控制器/服务等之前测试一下。


1
投票

您可以在脚本中包含/调用Drupal的引导程序,然后调用Drupal的函数。用于D7,但没有尝试D8。但它应该工作:

https://drupal.stackexchange.com/questions/174474/bootstrap-from-external-script

并从该页面复制代码:

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
        array(
          'type' => "article",
          'title'=> "test entity",
          'body' => "body body body",
        ));

$entity->save();

0
投票

您可以使用像这样的Devel和Kint模块运行drupal或非drupal的任何php代码。[使用Devel和Kint模块]像这样https://i.stack.imgur.com/RUKv6.png

© www.soinside.com 2019 - 2024. All rights reserved.