0

我正在从基于 Web 的 API 中获取用户数据,并且我想避免获取数据,因此如果我从不需要该数据就发出 HTTP 请求。我正在考虑创建一个在其构造函数User中接受 a并简单地存储它的类。如果在某个时间点调用任何 getter 方法,它会进行调用并从 API 获取数据。$userIDgetUserName()

现在,我创建了一个应该完成所有 API 工作的服务。我将如何将此APIWrapper服务连接到我的User实体类?我读到依赖实体类中的服务容器被认为是不好的风格。如果这是一个普遍首选的解决方案,我只会让User类依赖于服务容器并调用APIWrapper服务,通过User引用传递对象并让服务填写从 API 获取的所有内容。User但是如果类不依赖于服务容器,我怎么能做到这一点呢?

我希望能够像这样使用它:

$user1 = new User(1234);
$user2 = new User(2345);
echo $user2->getName();

它只会从 API 中获取 user2 的名称,而不会对 user1 执行任何操作。这样,我也可以轻松实现缓存,因此我什至根本不需要查询 API。

所以。什么被认为是做到这一点的最佳方式?

4

1 回答 1

0

If the user is authenticating and initially registering with a third-party service, you should probably just get that info right when they sign up. How many users do you expect to have who will never need to provide their basic account info?

It is indeed bad practice to inject services into an Entity, as an Entity's purpose is nothing more than to contain an object and its data. You should use a UserProvider for fetching the user data for an existing user, as described in various sets of guidelines for integrating the FOSUserBundle and the FOSFacebookBundle.

Now, when you do a Google search for integrating those two bundles, or when you ask around, you're going to be pointed to a paid screencast that costs $15. If you're really committed to Symfony as a framework for your projects, it may be worth your money to see how the people that build Symfony things think. If you are willing to deal with some pulling out of your own hair, you can dig deeper into the search results, and look at resources like this gist: https://gist.github.com/iBet7o/5215066.

Your exact implementation will depend on the bundles you're using, but in general, what your code should end up looking like is this:

function getName() {
    if($this->name == '') {
        return $this->getSignupProvider()->getUserinfo(); // or maybe just getProvider()
    }
    return $this->name;
}
于 2013-03-24T03:08:36.330 回答