Symfony2 entityManager in model - model-view-controller

I'm going to use entity_manager in my model. But entity_manager is only available in controller: throw $em = $this->get('doctrine.orm.entity_manager'). So, I have to define model methods with $em parameter. This is making phpUnit testing pretty difficult and violates application structure. For example:
class Settings
{
public static function getParam( $em, $key )
{
$em->createQuery("
SELECT s
FROM FrontendBundle:Settings s
WHERE s.param = {$key}
");
return $em->getResult();
}
}
Is there any approach to use entity_manager service in model section?

First, a starting note: by convention your Entity class should probably be singular. So, Setting, not Settings. You could argue that "settings" as a group of related settings could be seen as one entity. Still, something to bear in mind.
In Doctrine2, you would use a repository to make this type of query. In your code where you were going to call Settings::getParam, you would instead fetch the repository and query that. In symfony2, say:
// $em is your entitymanager, as you were going to pass to your method above
// $key is the key you were going to pass to your method above
$repository = $em->getRepository('\FrontendBundle\Settings');
$setting = $repository->getByParam($key);
By default, without writing any code, repositories define getByXXXX for each field in your entity.
If you have a more complicated query to make, you can extend the repository.
use Doctrine\ORM\EntityRepository;
class SettingsRepository extends EntityRepository
{
public function getBySomeComplicatedQuery() {
$sort_order = $this->getEntityManager()
->createQuery('SELECT count(s) FROM FrontendBundle\Settings s WHERE s.value > 32')
->getResult(Query::HYDRATE_SINGLE_SCALAR);
}
}
And then you'd call that method in the same way.
Others would advocate the use of a Manager object which would then not be tied to the Entity/ORM, but that's a needless complication in this case I think.
Doctrine2 is specifically designed to not let you use queries in your Entity file; Entities and EntityManagers are actually two aspects of the standard model layer, split apart to enforce best practices. See this article: http://symfony2basics.jkw.co.nz/get-symfony2-working/entities/

Queries in the Entity class
Putting queries in you entity seems odd to me. The same way as putting queries into your model class in Doctrine 1 it is not considered a good practice. Entity classes should be light.
I'm actually learning Doctrine2 and was thinking about similar problem: where to put queries?
In Doctrine 1 there are special Table classes and I was expecting something similar in Doctrine 2.
Repository Pattern
Today I learned that Doctrine 2 is using the Repository Pattern: http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-objects.html#custom-repositories
However, to retrieve an instance of repository class you need to use Entity Manager. One way or another you need it.
Still, following the repository pattern seems a better choice.
In my opinion If you insist on having query method in your Entity class you have to pass an Entity Manager to it.
Testing
Why the need of passing entity manager makes it hard to test? From my experience explicit dependencies make testing easier as you can control them in the test (and mock them for example).
On the other hand passing the entity manager to every method is not right choice either. In such case I'd make the dependency obligatory and add it to the contructor.

Related

2022-07-20: Repository pattern - Why exactly do we need Interfaces?

I know this has been asked quite a long time.
This was answered at 2012-03-16.
Repository pattern - Why exactly do we need Interfaces?
I never used repository one month ago. I use laravel: Controller, Service, Model, View.
Several months ago, I start to use trait. So many articles talk about interface, ok, one month ago, I start to use repository with interfaces. Now I feels that I'm doing things that seems not necessary.
There is Order model I forgot to draw. And I have to bind interface with repository in RepositoryServiceProvider
public function register()
{
$this->app->bind(RepositoryInterface::class, Repository::class);
$this->app->bind(MemberRepositoryInterface::class, MemberRepository::class);
$this->app->bind(OrderRepositoryInterface::class, OrderRepository::class);
$this->app->bind(OrderItemRepositoryInterface::class, OrderItemRepository::class);
//...
}
Now go back to that question's answer in 2012. Why we need to use interfaces? Because:
public class EmployeeRepositoryEF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying your EF DbContext
}
}
public class EmployeeRepositoryXML: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying an XML file
}
}
public class EmployeeRepositoryWCF: IEmployeeRepository
{
public Employee[] GetAll()
{
//here you will return employees after querying some remote WCF service
}
}
But with the bindings in RepositoryServiceProvider, we can not use these different repositories at the same time. I cannot imaging how. We have to change the bindings. But if so, why not just change the type hint in service layer?
Ok, I saw many articles actually use:
Controller > SomeRepositoryInterface $someRepository > Model
They don't have service layer.
Does it mean, since I have service layer, So I don't need interface?
Controller > SomeService $someService> SomeRepository $someRepository > Model
If we want to change repository, just do:
In SomeService:
use App\Repositories\Abc\SomeRepository;
or
use App\Repositories\Xyz\SomeRepository;
Then
use App\Repositories\Eloquent\Sale\OrderRepository;
use App\Repositories\Eloquent\Sale\OrderItemRepository;
use App\Repositories\Eloquent\Sale\RmaRepository;
use App\Repositories\Eloquent\Member\MemberRepository;
use App\Repositories\Eloquent\Member\MemberGroupRepository;
or
use App\Repositories\MSSQL\Sale\OrderRepository;
use App\Repositories\MSSQL\Member\MemberRepository;
or
use App\Repositories\Oracle\Sale\OrderRepository;
use App\Repositories\Oracle\Member\MemberRepository;
Eloquent can change driver to use mssql or oracle. Then...
use App\Repositories\DbBuilder\Sale\OrderRepository;
use App\Repositories\DbBuilder\Member\MemberRepository;
or
use App\Repositories\RawSql\Sale\OrderRepository;
use App\Repositories\RawSql\Member\MemberRepository;
or
use App\Repositories\AnyOtherKind\Sale\OrderRepository;
use App\Repositories\AnyOtherKind\Member\MemberRepository;
Can someone give me some suggestion?
Because we need a contract for the classes that people create over time. They should implement the same thing, and the customer should be able to use them interchangeably. If you don't have an interface, the next developer might forget implementing some methods and this means bad!
For example we have implemented our repositories to work with MySQL, and we exit the company. After a year, they plan for using something else rather than MySQL, so they have to implement new repositories that are compatible with the previous repositories and this is why we need an interface.
I hope my answer is simple and clear.
To begin with, using Repository pattern is bad with Active Record (which is Eloquent). AR (active record) models already have all the methods to all possible CRUD operations and scopes to encapsulate logic within. Using repositories over them is a good example of overengineering, so I'd recommend not using them at all in Laravel.
When working with DM (data-mapper) models, repositories are used to switch between different databases (like in your example in RepositoryServiceProvider). So, in case there is a need to change database over the project, you just create another implementation of repository for different database type. And again, in Laravel this is already done at query builder level, so you just don't need to do that by yourself.

Best approach for Dependency Injection in Laravel 5 package

I am developing a package for Laravel 5, and now I need to benefit from dependency injection to have a more scalable and relaible application, I don't know which approach is the best to take and why, this is a piece of my code and I need to injected the Lang class dependency
class MyController extends \App\Http\Controllers\Controller
{
public $text;
public $lang;
public function __construct()
{
// Some codes here
}
public function myFunction(){
$this->text = \Lang::get('package::all.text1');
}
}
In this link http://laravel.com/docs/4.2/ioc 2 approaches are suggested, Basic Usage and Automatic Resolution based on my understanding from the link
taking the first approach I need to add
App::bind('lang', function($app)
{
return new \Lang();
});
to the register part of application and then in the function I'll have something
like this :
public function myFunction()
{
$lang = \App::make('lang');
$this->text = $lang::get('package::all.text1');
}
The other way is to modify the constructor like
public function __construct(Lang $lang)
{
$this->lang = $lang;
}
And then instantiate object from Class like
$myController = App::make('MyController');
Which way is the better way to take for, considering that this class is a Controller and it will be called in the routes file, or please correct me if my understanding from the link is not right. please also inform me why you suggest any of those approaches.
It should be noted that using local IoC resolution ($app->make() stylee) is not much better than using the facades directly (Lang::get() stylee) - you're still very much relying on Laravel's specific classes without really making your code explicitly state that it needs these exact classes. So the general advice is to, as much as possible, code to an interface if you want your code to be as portable as possible.
Of course there are a couple of big downsides to this currently in PHP development:
These interfaces are not generally defined (except the PSR-3 LoggerInterface interface) so you still have to rely on a particular instance of the interface (in this case, Laravel's).
If you decide to make your own generic interface (or the FIG eventually creates some of these), the classes that Laravel provides for translation (for example) don't implement it anyway, so you then need to subclass the existing ones just to make it look like it implements your own interface. But hey, that's the current best practice, so I guess if you wanna be using the current best practices, code to an interface, and don't worry for the time being that the interface you're coding to is Laravel-specific.
But anyway, here are my thoughts on your specific question. First off I should say that I haven't actually used Laravel 5 yet (just the 4s), but I have generally followed its development.
If the class I am coding will use a given dependency quite a lot or as a core part of how the class works I will use constructor dependency injection. Examples here are the Request or some Repository class in a controller, or a business logic class in a console command class.
If what I need I only need for a specific purpose (maybe redirecting from a controller and needing to generate a URI) I will resolve a local version from the IoC container ($this->app->make()) and then use that. If I were using Laravel 5 and the method was called by Laravel directly (e.g. a controller's action method) I may use method injection for this, I'm not 100% sure.
As a final note, the general advice is that if your constructor method signatures get too big due to a lot of dependencies:
It's time to have a look at if your code relies too much on external dependencies. Maybe some of the functionality of your class can be extracted to its own class that splits the dependencies between the two.
You should consider using setter methods rather than constructor injection - so instead of accepting a Request object, you have a $class->setRequest() method. The downside of doing this is that you need to tell Laravel's IoC container how to instantiate your object (i.e. that these setters must be called). It's not that big a deal but something worth noting.
Relevant links:
Laravel 5's IoC article
Laravel 5's Controller injection advice

EF: Should entities have business logic?

I was wondering, should the entities have the capability to save changes to the context? Or have business logic that relates to that particular entity? For example:
ActionResult ResetPassword(UserViewModel viewModel)
{
var user = userCollection.GetUser(viewModel.Username);
user.ResetPassword();
}
where:
class User : Entity
{
public string Password{ get; set; }
public ResetPassword()
{
Password = ""
context.SaveChanges();
}
}
I find this a bit weird since the entity would have a reference to the context. I am not sure whether this would work either - or whether this is recommended. But I want to work on a domain where I do not have to worry about saving changes, at a higher level etc. How can I accomplish this?
Thanks!
Update
I have updated my example - hope its a bit clearer now :)
According to Domain-Driven Design domain objects should have behavior.
You should definately read this book:
I would keep my Entities as POCO's(Plain Old Class Objects, classes with only properties) and have a Repositary do methods like Insert / Update.
I can keep my Entities in a separate class library and use it in different places ( even in a different project), with a different Repository implementation.
In this Tutorial It is nicely explained, how to do a Repositary & Unit Of Work Patterns on an MVC project which uses Entity Framework
You may want to consider the UnitOfWork pattern between your controller and your entities.
http://martinfowler.com/eaaCatalog/unitOfWork.html

business methods in playframework contolles

Could somebody explain is it possible to have potected, pivate methods in playfamewok's contolles except:
public static void method-action-name() {}
For example if I would have method like this:
protected static int doSomeWork() {}
and this method would be invoked in method-action-name() ..
public static void method-action-name() {
...
int resul = doSomeWork();
...
}
I do not want to have long action-method, so I would like to split it to smaller ones, and then reuse it in other action-methods.
I mean is it ok (from playframework's point of view) to have such method in controller side instead of having them in domain classes? In Spring Framework, we use BP (business process) beans for that, for example.
Is it ok to have such helper methods for business methods in playframework controllers ?
Added after having answer & comments:
For example if I have SearchController class then for that class would be nice to have methods like preSearch1(), preSearch2() what search() method would use, but if I move these methods (1,2) to another class then it should be class with name like SearchHelper then? in package named /src/helpers.. not very nice because they related to search too. But maybe then into /src/bp/SearchBP (bp=business-process). And then in controllers/Search i use /bp/SearchBP that use some Model object with .save() DAO methods (SearchBP can use Domain methods and Search class can use Domain methods as well)
The question here: what class ant package would be nice for those methods? (i just did watch it in examples - there alway very simple usage of controllers that use domain object that why i ask)
yes, you can. Controllers are normal classes, you can add whatever you want. It may not be recommended to clutter them with helper methods, I personally would move them to another class, but you can do what you say.
ANSWER TO EDIT:
The name of the package is "irrelevant", won't change it too much :). You can put them under controllers.support.search which would mean controllers.support is a package with helper classes and the subpackage search contains helper classes and methods related to search.
One alternative (which I like more) is to create a Service layer for that, in a "services" package. You seem to come from a Spring background, so it should come naturally to you. These services are instantiated in the controller as required, or maybe just used via static methods, and do the main business logic. That way the controller only tackles the "higher level" logic.
Another alternative is to move as much of that logic as possible into the Model (avoidid the Anemic Domain Model), and using the Model classes from the controller.
As most decisions in development, which one is better depends on your experience, possible impact/limitations in the codebase, practices in your project... anyway, you can always refactor. Just choose the one that you are more used to (it seems to be Services approach) and code away :)
Any behaviour that's complicated enough to be described as "business logic" (rather than "presentation logic") belongs in the model, not the controller. If your model does nothing but map to/from a set of database tables, then it isn't doing its job properly. Things like permissions and access control, in particular, should be enforced by the model.

TDD-friendly Singleton-like class

I have repository class that is used by at least 2 other classes. This repository class needs to be initialized - which is high in cost (querying database). Now, I create separate instances of repository wherever I need it. The thing is, that everytime I create repository it has to be initialized. How to design such repository to be TDD-friendly? The first thing in my mind was Singleton but it's not the solution.
I hope by TDD-friendly you mean 'testable' code. For a Singleton ObjectX, I think the most common way is to split the responsibility (SRP) of 'controlling creation' to another class so ObjectX does all the things it is supposed to do.
Then you have another class ObjectXFactory or Host or whatever you wanna call it that is responsible for providing a single instance for all clients (and providing thread sync if needed and so on)
Object X can be TDDed independently. You can create a new instance in your test case and test functionality.
ObjectXFactory on the other hand is also easy to test.. you just need to see if multiple GetInstance() calls return the same object. OR better delegate this responsibility to an IOC framework like Spring, which lets you declaratively mark an object definition to obtain singleton behavior (Saving you the effort of writing tests as well)
You just need to educate and conform to a Team convention that ObjectX constructor is not to be called - always use ObjectXFactory.CreateInstance(). (If you find that you have a awareness/discipline problem, mark ObjectX's ctor as internal and visible to only to the test assembly via the sneaky InternalsVisibleToAttribute)
HTH
One answer for the TDD part is learn mocking.
Check out this excellent article by Stephen Walther:
http://stephenwalther.com/blog/archive/2008/03/23/tdd-introduction-to-rhino-mocks.aspx
Do you use any type of IOC container? Unity is my container of choice, and it contains a ContainerControledLifetimeManager which makes your class a singleton, but not managed by yourself.
Consider caching instances for performance improvement before you consider singletons. But for TDD friendly designs consider strategy injection so that 'slow' bits can be removed for testing and replaced with stubs and mocks. Try not to do db calls in tests if you can.
You can't do that -- at least not in a true TDD sense.
Relying on DI/IoC strategies such as Unity means your tests are dependent on an external component and are not tested in isolation.
The tests then become integration tests, not unit tests.
==Ignore the answer below here==
I guess you wanted to know how to make Repository testable.
Introducing an interface for it would allow you to mock or stub it, which will in turn make sure that you can test your objects independent of any concrete implementation of Repository.
I'll illustrate this using Rhino Mocks 3.5 for .NET 3.5:
Let's make an interface out of Repository, let's call that IRepository
public interface IRepository
{
}
Now, since you need to use IRepository for two different objects, then let's just use generics so you can instantiate your repository with that:
public interface IRepository<T>
of course that would mean that you would have some sort of find method:
{
public IEnumerable<T> Find(Criteria criteria)
}
where your criteria object is some object that allows you to set what to look for, e.g., your where clause.
Now, you have your object:
public class SomeObject
{
IRepository<SomeObject> repository;
public SomeObject(){}
public IRepository<SomeObject> repository { get; set; }
IEnumerable<SomeObject> FindAll()
{
//let's assume new Criteria() will return all results
return respository.Find(new Criteria());
}
}
You want to to test SomeObject such that FindAll() will return an expected set of results -- this is where Rhino Mocks would come in:
[TestFixture]
public class SomeObjectTests
{
[Test]
public void TestSomeObjectFindAll()
{
IRepository<SomeObject> stubRepository = MockRepsitory.GenerateStub<IRepsitory<SomeObject>>();
stubRepository.Expect(r => r.Find(new Criteria())
.Return(new List<SomeObject>{
new SomeObject(),
new SomeObject(),
new SomeObject());
var testObject = new SomeObject { Repository = stubRepository };
IList<SomeObject> findAllResult = testObject.FindAll();
//returned list contains 3 elements, as expected above
Assert.AreEqual(3, findAllResult.Count)
}
}
Note that the code above is not TDD best practice in all respects, but it's a place to start.
Key concept here is introducing interfaces to allow for loose coupling of objects, especially when the object tends to do things like access databases, file systems, etc.
There is a more comprehensive example and better examples on Ben Hall's article on Rhino Mocks.

Resources