简体   繁体   中英

Symfony3 - Define service outside src/bundle

I am trying to define service outside src, in App\\Service to be exact. I know that service in Symfony is just a class therefore I should be able to put it anywhere.

That's what I've got at the moment:

app\\config\\services.yml

parameters:
  serializer_service_class: App\Service\SerializeService

services:
    app.serializer:
        class: '%serializer_service_class%'
        autowire: true

Service is just a simple serializing class:

SerializeService.php

<?php

namespace App\Service;

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

/**
 * Class SerializeService
 * @package App\Service
 */
class SerializeService
{
/**
 * @var Serializer
 */
private $serializer;

/**
 * @var array
 */
private $encoders;

/**
 * @var array
 */
private $normalizer;

/**
 * SerializeService constructor.
 */
public function __construct()
{
    $this->encoders = array(new XmlEncoder(), new JsonEncoder());
    $this->normalizer = new ObjectNormalizer();

    $this->normalizer->setCircularReferenceHandler(function ($object) {
        return $object->getId();
    });

    $this->serializer = new Serializer($this->normalizer, $this->encoders);
}

public function serialize2Json($item)
{
    return $this->serializer->serialize($item, 'json');
}

}

Then I get this error message:

Attempted to load class "SerializeService" from namespace "App\Service".
Did you forget a "use" statement for another namespace?

I've really tried to find solution for this and I have tried different options. If it is somewhere on stackoverflow please point me to this post.

Thanks in advance.

As Pib Ball said your autoloader is probably missing some infos.

I've tried the following setup

myProjectRoot/
    app/
        config/
        Resources/
        Service/
            SerializeService.php <- your service file

I have used your code, no changes.

I have the same error as you, then I've edited my composer.json as following

................
"autoload": {
    "psr-4": {
        "": "src/",
        "App\\": "app/",
    }
},

Then executed the command composer update and then your service should be loaded.

Hope it may helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM