Пример настройки облачного хранилища Google с помощью KnpGaufetteBundle

Я пытаюсь настроить KnpGaufretteBundle для использования Google Cloud Storage для хранения моих файлов. Это конфиг:

## definition of the GCS service
app.google_cloud_storage.service:
    class: \Google_Service_Storage
    factory_class: Knp\Bundle\GaufretteBundle\DependencyInjection\Factory\GoogleCloudStorageAdapterFactory
    factory_method: 'create'
    arguments: 
        - "[email protected]"
        - "http://localhost/file.p12"
        - "pwd"

## config of knp_gaufrette
knp_gaufrette:
    stream_wrapper: ~
    adapters:
        gcs_minn_images:
            google_cloud_storage:
                service_id: 'app.google_cloud_storage.service'
                bucket_name: 'minn-images'
    filesystems:
        gcs_minn_images_fs:
            adapter: gcs_minn_images 

Сообщение об ошибке, которое я получил:

ContextErrorException в строке 16 GoogleCloudStorageAdapterFactory.php: Обнаруживаемая неустранимая ошибка: аргумент 1 передается в Knp\Bundle\GaufretteBundle\DependencyInjection\Factory\GoogleCloudStorageAdapterFactory::create() должен быть экземпляром Symfony\Component\DependencyInjection\ContainerBuilder, указанная строка , вызываемый в /home/amine/NetBeansProjects/tuto/app/cache/dev/appDevDebugProjectContainer.php в строке 724 и определяемый

Согласно сообщению об ошибке я дал строку вместо ContainerBuilder. Здорово! Давайте добавим ContainerBuilder к аргументам следующим образом:

## definition of the GCS service
app.google_cloud_storage.service:
    class: \Google_Service_Storage
    factory_class: Knp\Bundle\GaufretteBundle\DependencyInjection\Factory\GoogleCloudStorageAdapterFactory
    factory_method: 'create'
    arguments: 
        - @service_container
        - "[email protected]"
        - "http://localhost/file.p12"
        - "pwd"

В итоге снова ошибка:

Перехватываемая неустранимая ошибка: аргумент 1, переданный в Knp\Bundle\GaufretteBundle\DependencyInjection\Factory\GoogleCloudStorageAdapterFactory::create(), должен быть экземпляром Symfony\Component\DependencyInjection\ContainerBuilder, заданным экземпляром appDevDebugProjectContainer, вызываемым в /home/ amine/NetBeansProjects/tuto/app/cache/dev/appDevDebugProjectContainer.php в строке 724 и определено

Итак, теперь ошибка говорит мне, что я предоставляю экземпляр appDevDebugProjectContainer вместо ContainerBuilder!!

Хорошо, давайте посмотрим на /home/amine/NetBeansProjects/tuto/app/cache/dev/appDevDebugProjectContainer.php в строке 724...

class appDevDebugProjectContainer extends Container{
// ...
/**
 * Gets the 'app.google_cloud_storage.service' service.
 *
 * This service is shared.
 * This method always returns the same instance of the service.
 *
 * @return \Google_Service_Storage A Google_Service_Storage instance.
 */
protected function getApp_GoogleCloudStorage_ServiceService()
{
    return $this->services['app.google_cloud_storage.service'] =\Knp\Bundle\GaufretteBundle\DependencyInjection\Factory\GoogleCloudStorageAdapterFactory::create($this, '[email protected]', 'http://localhost/file.p12', 'pwd');
}

Я действительно потерялся... Итак, есть ли какой-нибудь полный пример для настройки облачного хранилища Google?


person Amine Jallouli    schedule 14.11.2015    source источник


Ответы (1)


Я наконец нашел решение. Вы должны создать свой собственный фабричный класс, как описано в документации пакета:

Заводской класс

<?php

namespace Minn\AdsBundle\Factory;
/**
 * Description of GoogleCloudStorageServiceFactory
 */
class GoogleCloudStorageServiceFactory {

    public function createService() {
        // creating the google client
        $client = new \Google_Client();

        // setting the service acount credentials
        $serviceAccountName = '[email protected]';
        $scopes = array(
            'https://www.googleapis.com/auth/devstorage.read_write',
        );
        $privateKey = file_get_contents('http://localhost/f.p12');
        $privateKeyPassword = 'pwd';

        $credential = new \Google_Auth_AssertionCredentials(
                $serviceAccountName, $scopes, $privateKey, $privateKeyPassword);

        // set assertion credentials
        $client->setAssertionCredentials($credential);

        // creating and returning the service
        return new \Google_Service_Storage($client);
    }

}

Файл config.yml

app.google_cloud_storage.service:
    class: \Google_Service_Storage
    factory: [Minn\AdsBundle\Factory\GoogleCloudStorageServiceFactory, createService]


knp_gaufrette:
    stream_wrapper: ~
    adapters:
        gcs_images:
            google_cloud_storage:
                service_id: 'app.google_cloud_storage.service'
                bucket_name: 'images'
filesystems:
    gcs_images_fs:
        adapter: gcs_images

vich_uploader:
    db_driver: orm
    storage: gaufrette   
    mappings:
        motors_files:
            upload_destination: gcs_images_fs
            namer: vich_uploader.namer_origname
            delete_on_remove: true

Вот это было...

Надеюсь, это поможет другим...

person Amine Jallouli    schedule 23.11.2015