Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

Communication between Symfony and Doctrine on different projects

The application is split into several projects.

The database is a separate project and use doctrine (without Symfony).

The API is a symfony project which uses the database project as dependencies (vendor).

I would like to create events at the Symfony level by listening to doctrine event, but Symfony does not know any doctrine because it is external to its project.

Do you have an idea ?

Thanks

question from:https://stackoverflow.com/questions/65933652/communication-between-symfony-and-doctrine-on-different-projects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand correctly, you have two Symfony applications - the first one with a database and the second one that uses this database via API. It's not possible to implement Doctrine events listener within the second application, as it's not aware of Doctrine entities of the first application. However, you can solve this problem by using Symfony Messenger Component. The first application would dispatch messages on every Doctrine event and the second application would subscribe to those messages and handle them.

Something like this. The first application side.

<?php

declare(strict_types=1);

namespace AppEventListener;

use AppEntityUser;
use AppMessageUserChangedNotification;
use DoctrinePersistenceEventLifecycleEventArgs;
use SymfonyComponentMessengerMessageBusInterface;

class UserChangedNotifier
{
    private MessageBusInterface $bus;

    public function __construct(MessageBusInterface $bus)
    {
        $this->bus = $bus;
    }

    public function postUpdate(User $user, LifecycleEventArgs $event): void
    {
        $this->bus->dispatch(new UserChangedNotification($user));
    }
}

The second application side.

<?php

declare(strict_types=1);

namespace AppMessageHandler;

use AppMessageUserChangedNotification;
use SymfonyComponentMessengerHandlerMessageHandlerInterface;

class UserChangedNotificationHandler implements MessageHandlerInterface
{
    public function __invoke(UserChangedNotification $message)
    {
        // ... do something with the message, e.g. dispatch Symfony event
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...