Cakephp 4 Slug 生成

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

我有一个问题。我正在根据他们官方网站上的指南在 Cakephp 中构建一个 CMS。一切都很顺利,但我有一个问题。 正如文章所补充的,没有生成任何服务。 一切都按照教程 100% 完成。

你能猜出是什么原因造成的吗?

我把它放在ArticlesTable中,但似乎不起作用。

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

class ArticlesTable extends Table
{
    public function beforeSave($event, $entity, $options)
    {
        if ($entity->isNew() && !$entity->slug) {
            $sluggedTitle = Text::slug($entity->title);
            $entity->slug = substr($sluggedTitle, 0, 191);
        }
    }

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('articles');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Editions', [
            'foreignKey' => 'edition_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER',
        ]);
        $this->hasMany('ArticlesComments', [
            'foreignKey' => 'article_id',
        ]);
        $this->hasMany('ArticlesGalleries', [
            'foreignKey' => 'article_id',
        ]);

    }

有什么想法吗?

php cakephp content-management-system slug cakephp-4.x
1个回答
0
投票

如果有人在 2023 年通过 CakePHPCookbook 遇到这个问题。

  1. 确保将其添加到 ArticlesTable.php (src/Model/Table/ArticlesTable.php
  2. 确保您已添加以下使用语句:
use Cake\ORM\Table;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

我只能让它按照这个确切的顺序工作,如果 use 语句的顺序与我的不同,则不会生成 slugs。

完整代码:

<?php
// src/Model/Table/ArticlesTable.php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Utility\Text;
use Cake\Event\EventInterface;

class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);
        $this->addBehavior('Timestamp'); // automatically adds created and modified columns
    }

    public function beforeSave(EventInterface $event, $entity, $options)
    {
        if($entity->isNew() && !$entity->slug)
        {
            $sluggedTitle = Text::slug($entity->title);
            //trim slug to max. length
            $entity->slug = substr($sluggedTitle, 0, 191);
        }
    }
}

?>

这是特定于 CakePHPCookbook(2023 年 11 月 24 日版本)5.x 的第 56 页,因此以后可能不准确。

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