drupal 8 以编程方式创建节点只能成功一次

drupal 8 programmatically create node can only succeeded once

我在 Drupal 8 中创建了一个新模块,它只是一个 hello world 示例。 代码如下

class FirstController{
public function content(){
return array(
      '#type' => 'markup',
      '#markup' => t('G\'day.............'),
    );

// <------I added the new node code here
}
}

并且我将以下代码添加到 content() 函数以创建节点。 但是我发现它只能创建一次节点,之后无论我刷新模块页面多少次都不会再创建新节点。

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();

我做错了什么吗?

你忘了缓存 :) 你的输出只是被缓存了,这就是为什么你的代码只被调用一次(更准确地说,不是一次,而是直到缓存有效)。看这里:Render API and here: Cacheability of render arrays.

要禁用当前页面请求的缓存,您可以使用以下代码:

\Drupal::service('page_cache_kill_switch')->trigger();

因此,您的控制器方法可能如下所示:

public function content() {

  // Create file object from remote URL.
  $data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
  /** @var FileInterface $file */
  $file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_RENAME);

  // Create node object with attached file.
  $node = Node::create([
    'type'        => 'article',
    'title'       => 'Druplicon test',
    'field_image' => [
      'target_id' => $file->id(),
      'alt' => 'Hello world',
      'title' => 'Goodbye world'
    ],
  ]);
  $node->save();

  \Drupal::service('page_cache_kill_switch')->trigger();

  return array(
    '#markup' => 'Something ' . rand(),
  );
}