Shopping cart with Symfony2

有些话、适合烂在心里 提交于 2019-12-03 16:38:49

The general rule when creating Entities and Repositories is that an Entity class should contain the logic needed to operate on a single Entity, and Repository classes contain the logic needed to operate on groups of Entities.

A simple example:

  • If you wanted to convert the price of an item from dollars to euros, you would have BasketItem::convertCurrencyTo($currencyType). This is code that operates on a single Entity.

  • If you wanted to find all BasketItems whose price is between $10 and $20, you would use BasketItemRepository::findByPriceRange($min, $max). This is code that operates on a group of Entities.

IMO, things can get a little confusing when dealing with Entities that have a one-to-many or many-to-many relationship. I would imagine that one Basket has many BasketItems, and one User has one Basket. Therefore, I think it's reasonable to assume that in order to fetch the BasketItems a User is interested in, you could do something like this:
$user->getBasket()->getBasketItems().

Note that there is no Repository being used in this example because it's a very basic query. If you needed to do something more specific, like find the BasketItems a User is interested in that happen to be on sale, you could use something like BasketItemRepository::findWhereOnSaleForBasket($BasketId). There's nothing stopping you from adding a similar method directly to the User or Basket classes, but I feel that because your query's main 'target' is a BasketItem, it belongs in that Entity's Repository class.

You mention that implementing a shopping cart is no small task, and you're right. But the questions you're asking aren't really limited to Symfony2 (in this case it's more about Doctrine 2), so I think it might be helpful if you check out other open source shopping carts and study what they're doing. I think the only impact Symfony2 would really have is forcing you to decide how to split up your code within bundles.

Hope this helps!

There is an ecommerce bundle available called Vespolina which also provides a cart.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!