我正在使用 CakePHP 3.4+
我已经用multi level membership
.
成员将Pro
受益于查看外部链接的短网址,共享时将记录对该网址的访问次数。
原始 url 存储在PostVideos
所有用户的表中。
我创建了一个表来存储uniuqe keys
里面short urls
的short_video_post_urls
列
+----+---------------+------------+-------------+
| id | post_video_id | unique_key | visit_count |
+----+---------------+------------+-------------+
由于 Pro 成员的数量将低于普通用户,我不想生成unique_key entry
,short_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()