1

我正在使用 CakePHP 3.4+

我已经用multi level membership.

成员将Pro受益于查看外部链接的短网址,共享时将记录对该网址的访问次数。

原始 url 存储在PostVideos所有用户的表中。

我创建了一个表来存储uniuqe keys里面short urlsshort_video_post_urls

+----+---------------+------------+-------------+
| id | post_video_id | unique_key | visit_count |
+----+---------------+------------+-------------+

由于 Pro 成员的数量将低于普通用户,我不想生成unique_key entryshort_video_post_urls因为它会用无用的记录淹没数据库。

所以,我想要的是动态生成它们并仅为 PRO 成员存储它们

现在,在template$postVideo->video_url用来显示post_videos表格中的原始视频网址的文件中。

问题

我想要的是调整video_url将检查的实体调用

  • 登录用户的会员等级
  • 如果会员是专业人士
    • ShortVideoPostUrls检查请求的 url的模型中是否存在唯一键
    • 如果不存在记录,则在ShortVideoPostUrls
    • 返回新的网址unique_key

但为此我需要访问logged_in实体类中的用户数据。

我试过什么?

class PostVideoLog extends Entity
{
    /*
     * ----
     * ----
    */

    protected function _getVideoUrl()
    {
        $user = $this->Users->get($this->Auth->user('id'), [
            'contain' => [
                'MembershipLevels'
            ]
        ]);

        if ($user) {
            if (strtolower($user->membership_level->title) === 'pro') {
                /**
                 * check if unique_key exists for this request
                 */
                $checkShortUrl = $this->ShortVideoPostUrls->find()
                    ->where(['post_video_log_id' => $this->_properties['id']])
                    ->first();

                if ($checkShortUrl) {
                    return $this->_generateUrl($checkShortUrl->unique_key);
                }

                /**
                 * create new record
                 */
                $unique_key_generator = new Hashids(UNIQUE_SHORT_URL_SALT, 4);
                $unique_key = $unique_key_generator->encode($this->_properties['id']);

                $newShortUrl = $this->ShortVideoPostUrls->newEntity();
                $newShortUrl = $this->ShortVideoPostUrls->patchEntity($newShortUrl, [
                    'unique_key' => $unique_key,
                    'post_video_log_id' => $this->_properties['id']
                ]);

                if ($this->ShortVideoPostUrls->save($newShortUrl)) {
                    return $this->_generateUrl($unique_key);
                }
            }
        }

        return $this->_properties['video_url'];
    }

    private function _generateUrl($unique_key)
    {
        $base_url = Router::url('/', true);

        return $base_url . '/u/' . $unique_key;
    }
}

我不确定我的方法是对还是错。

要加载Users我在上述功能中使用的模型和其他模型,需要使用

$this->loadModel('Users');

但是,loadModel似乎不在这里工作。

还有什么其他方法可以做到这一点?或者如何在 Entity 类中加载外部模型和 Auth 组件?

编辑 2

在没有实体的情况下,有没有更好的选择来做我想做的事?或者只是某种从template每个实体调用函数的方法?

前任。

$postVideo->video_url()
4

1 回答 1

0

在实体中加载其他模型您可以使用TableRegistry

use Cake\ORM\TableRegistry;

class MyModel extends Entity {

    protected function _getVideoUrl() {

        $table = TableRegistry::get('Users');
        $users = $table->find('all')->toArray();
    }
}

我认为在模型中使用Auth组件不是最好的主意-我不知道如何“正确”执行此操作,但是所有会话数据(包括身份验证数据)仍然可以在$_SESSION数组中使用

于 2017-11-08T20:33:03.033 回答