[英]Sonata Media: Change context programmatically
我正在寫一個小博客應用程序,用戶可以在其中發布公共和私人新聞。 用戶可以將文件附加到這些新聞。 這個應用程序有兩個上下文: public_news
,每個人都可以訪問的文件; 和private_news
,只有在用戶登錄后才能訪問的文件。
當用戶將新聞從公共更改為私人時,我希望能夠將文件從public_news上下文移至private_news上下文,反之亦然。
我希望做像$media->setContext('private_news');
這樣簡單的事情$media->setContext('private_news');
,但這不會將物理文件從一個目錄移動到另一個目錄。
您如何看待這種媒體?
$oldMedia = getYourOldMedia();
// $media = clone($oldMedia); # For me it didn't work as expected
# YMMV - I didn't spend lots wondering about that
$media = new Media();
// This will work fine with image and file provider,
// but it was not tested with other providers
$pool = $container->get('sonata.media.pool');
$provider = $pool->getProvider($oldMedia->getProviderName());
$media->setBinaryContent($provider->getReferenceFile($oldMedia));
}
$media->setProviderName($oldMedia->getProviderName());
$media->setContext('private_news');
/* copy any other data you're interested in */
$mediaManager->save($media);
$mediaManager->delete($oldMedia);
$mediaManager->delete
可能不會刪除您的物理文件,具體取決於提供程序,您可能希望創建自己的提供程序。
在進一步研究中,我發現您可以在刪除舊媒體之前手動刪除文件:
if ($pool->getFilesystem()->has($path)) {
$pool->getFilesystem()->delete($path);
}
但是在保存新的媒體實體之前不要這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.