2016-02-29 38 views
1

我正在制作Silverstripe构建任务以从外部图库获取许多图像,并使用必要的数据库链接将其创建/上载到/assets/images/gallery文件夹中,并链接至GalleryPage通过BuildTask将外部图库中的图像添加到SilverStripe网站

因此,我加载Url列表,将图像显示到浏览器,现在如何将图像保存到资产文件夹中,并提供必要的GalleryPage数据库链接?

class ImportGalleryTask extends BuildTask { 
    public function writeImage($data) { 
     //$data->Title 
     //$data->Filename 
     //$data->Url 
     //this is the external url that I can output as an image to the browser 
     // 
     // folder to save image is 'assets/images/gallery' 
     // 
     // ? save into folder and database and associate to PageImageBelongsToID ? 
    } 
} 

回答

2

您可以使用copy将远程文件复制到本地文件系统。尽管PHP必须被配置为支持allow_url_fopen

所以,你得到的函数可能是这样的:

/** 
* @param $data 
* @return null|Image return written Image object or `null` if failed 
*/ 
public function writeImage($data) 
{ 
    // The target folder for the image 
    $folder = Folder::find_or_make('images/gallery'); 

    // assuming that $data->Filename contains just the file-name without path 
    $targetPath = $folder->getFullPath() . $data->Filename; 

    // Check if an image with this name already exists 
    // ATTENTION: This will overwrite existing images! 
    // If you don't want this, you need to implement this differently 
    if(
     file_exists($targetPath) && 
     $image = Image::get()->where(array(
      '"Name" = ?' => $data->Filename, 
      '"ParentID" = ?' => $folder->ID 
     ))->first() 
    ){ 
     // just copy the new file over… 
     copy($data->Url, $targetPath); 
     // … and delete all cached images 
     $image->deleteFormattedImages(); 
     // and we're done 
     return $image; 
    } 

    // Try to copy the file 
    if (!copy($data->Url, $targetPath)) { 
     return null; 
    } 

    // Write the file to the DB 
    $image = Image::create(array(
     'Name' => $data->Filename, 
     'ParentID' => $folder->ID, 
     'Filename' => $folder->getRelativePath() . $data->Filename 
    )); 

    $image->write(); 
    return $image; 
} 
+0

十分感谢,这个工程的复制图像和数据库中识别它,但是它并没有将其与它应该属于关联页,那就是GalleryPage。该图像需要属于GalleryImage类,GalleryImage类有一个PageImageBelongsToID,它是一个GalleryPage类,我该怎么做? – user3257693

+1

@ user3257693嗯,这取决于。如果你有一个GalleryPage,那么你可以得到它:'GalleryPage :: get() - > first()'。否则,你将不知何故必须告诉导入任务您要导入的GalleryPage ...可能是传递ID作为参数。 – bummzack

+0

@ user3257693也,子类化图像来创建一个关系是一个非常糟糕的主意。我认为有几种情况下系统会为你创建一个Image,而不是你想要的子类(例如,如果你通过CMS取代你的图像)。我强烈建议你使用扩展,而不是使用'many_many'关系,这样就可以将图像附加到多个页面。 – bummzack