Doctrine Custom Repository vs Entity Methods Best Practice - doctrine-orm

You can traverse entities using entity methods, and you can do exactly the same using entity repository, the difference is that you will make extra class and attach it to the entity and the repository also will create some kind of confusion to other developers to know if a certain method is available, they will need to check the entity and the repository.
Is there any other difference? is there any benefit of using custom repositories ? or what is the best practice to handle such situation?

Generally:
methods in an entity should be connected only to this particular entity object (the exception are getter / setter with relations).
methods in a repository should be connected to whole entity class
For example: if you have an Article entity you may create "slugify" method inside entity because you want make slug from title for this particular object.
But if you need, let say, get all articles which are older than one year - you will make such method in repository (because it's not related to any particular object)

Related

Selecting a design pattern to assing different objects via an interface, based on a user made configuration

Currently am I working on a by user configurable controller.
The user can configure the modules which are objects of the same or different classes, all returning one or more variables as integer or boolean.
The user can configure the links between the just configured objects as they can request each others return data via a method.
A execution manager executes the highest object in the configuration of which the return values are not used by other objects. The highest object will require as configured by the user, return data from other objects via their methods. These methods "activate" the object of which data is requested, and will further down ask return data from other objects.
I am planning to write this software in c++ an shall be running on a cortex-m4 microcontroller.
I have bin looking in to several design patters but cant find any matching one, suiting my needs. So i made my own design but am not totally convinced of it being the perfect solution.
My design so far:
a abstract base class acts as an interface for creation.
a class inheriting the base class Decorates the module.
an other base class acts as an interface to access a single bool or integer.
a class inheriting the "other base class" contains the actual algorithm to access the method to retrieve the data from the module.
Meaning:
for every single by configuration linkable bool or integer is an object created to retrieve the data, returning it via a standard base interface.
this means that Every module can have any number of variables only each resulting when used in a single object per variable.
Is there any other, more efficient design pattern than my "Brand pattern", creating less overhead but also providing the same run time flexibility?
MvG Robbert

Serializing look up object for App Fabric

I have to cache a set of lookup collection based on several objects. In other to use app fabric, the underlying object has to be serializable. My issue is that I have over 100 object that could potentially be cached and going and marking each of them with the [serializable] attribute just seems wrong to me. Since all of this object derive from a base class, I would think marking the base class as serializable would make the derived class serializable but attributes do not work with inheritance. Does enyone know how to go about making all these classes serializable without marking each of them with the property ? Can I make all classes in a namespace serializble for instance, in which case I can put all of them in a library.
Unless you're using the Azure version of AppFabric then you will just have to make the classes serializable, as IDataCacheObjectSerializer never made it into the Windows Server version of AppFabric.

How to inject an abstract factory into an entity's method?

I have an Order entity with a refund() method that uses an abstract factory refundStrategyFactory to create the appropriate refund strategy at run-time:
public class Order extends Entity{
public void refund(Employee emp, Quantity qty, IRefundStrategyFactory refundStartegyFactory){
//use the abstract factory to determine the appropriate strategy at run-time.
}
}
I'm trying to use dependency injection and have IRefundStrategyFactory injected automatically into the refund() method, but I couldn't find a way to achieve this.
I'm not using the constructor injection because Order is an entity and we shouldn't inject services into entities unless it's going to be used temporarily as in the refund method. This is better explained by Misko Hevery's blog post To “new” or not to “new”…:
It is OK for Newable to know about Injectable. What is not OK is for
the Newable to have a field reference to Injectable.
A similar answer by Mark Seemann to a related question also advocates the same idea.
Bonus point, Aren't I exposing the internals of the refund() method by exposing its dependency on IRefundStrategyFactory? Should I sacrifice unit testing in isolation and create the factory inside the method itself?
Well ideally your domain model should be free infrastructure concerns and IOC is a infrastructure concern, it is recommended that the domain model be simple POJO's. So I would not inject beans into my domain model.
In this case i think you should have a application service which gets injected the factory class and it then just passes the factory class as a parameter to your Order class.
Does the factory class use some information from the Order class to decide which kind of strategy class to instantiate ?
Bonus point, Aren't I exposing the internals of the refund() method by
exposing its dependency on IRefundStrategyFactory?
I am not sure if there is such a thing as exposing the internals of a method, This concept fits more naturally with "exposing internals of a class", A method does some action and to do so it might need some information from the outside world, we could debate on how to pass in that information and whether that one method is doing too much or not ? ... But i cannot reason on whether a method "exposes its implementation", maybe you should elaborate on what you meant by that point
I'd solve this by starting a refund process with eventual consistency, where you trigger a Refund action. The listeners to this action and it's events would then do their own tasks, i.e. refund the cost of the goods, restock the items, etc. Alternatively you could just do this atomically in an application service that triggers several domain services, one after another, passing in the Order item:
FinancialService.RefundOrderGoods(myOrder);
StockService.RestockOrderItems(myOrder);
...
I'd avoid adding any services or repositories into your entities.
Your main problem is that you can't "injected automatically into the refund() method", but IMO that isn't a problem at all, since you can simply pass on the dependency onto the method but still use constructor injection in the service that calls this method:
public class ApplyRefundHandler : ICommandHandler<ApplyRefund>
{
private readonly IRefundStrategyFactory refundStartegyFactory;
private readonly IRepository<Order> orderRepository;
private readonly IRepository<Employee> employeeRepository;
public ApplyRefundHandler(IRefundStrategyFactory refundStartegyFactory,
IRepository<Order> orderRepository,
IRepository<Employee> employeeRepository)
{
this.refundStartegyFactory = refundStartegyFactory;
this.orderRepository = orderRepository;
this.employeeRepository = employeeRepository;
}
public void Handle(ApplyRefund command)
{
Order order = this.orderRepository.GetById(command.OrderId);
Employee employee = this.employeeRepository.GetById(command.EmployeeId);
order.refund(employee, command.Quantity, this.refundStartegyFactory);
}
}
Aren't I exposing the internals of the refund() method by exposing its
dependency on IRefundStrategyFactory? Should I sacrifice unit testing
in isolation and create the factory inside the method itself?
Yes you are, but in the same time you are probably violating the Single Responsibility Principle by adding a lot of business logic in the Order class. If you hide the abstractions, it means you need to inject them into the constructor and you will probably find out quickly that your Order class gets a lot of dependencies. So instead you can view the Order's methods as a Single Responsibility (a class in disguise) that has little to no relationships with the other methods in that class, and in that case it makes sense to pass in its dependencies into that method.
As a side node, please be aware that factory abstractions, like your IRefundStrategyFactory are usually not good abstractions. You should consider removing it, as described in detail here.

How to verify method class in test class

I have a repository with a method called ConvertToBusinessEntity which converts the data from the data source to a business object. This method is supposed to be used by other methods in the repository namely the Get, GetAll, etc.
This method is unit tested. I check if the data is being retrieved correctly from the data source and the values are being put in the entity correct properties.
But now I need to test and create the GetEntity method which is supposed to call ConvertToBusinessEntity. The logic behind ConvertToBusiness is tested. I just need to know how to verify that a method in the class being tested is called (not a dependency).
Does anyone know how to do this or any alternative method?
I thought of an alternative method but I am not sure if it's the best. I could extend the class under test and have a counter increasing each time the method is called.
Another one would be to mock the class itself.
What do you think? Any other suggestions?
Having ConvertToBusinessEntity in repository is not very good idea. Responsibility of repository is working with data store (CRUD). Mapping of data types is responsibility of some mapper class. Otherwise your repository has too many responsibilities. Take a look on what you are trying to test:
I check if the data is being retrieved correctly from the data source
and the values are being put in the entity correct properties
You see this and? Your test can fail on two completely different reasons. Also you should change repository on two completely different reasons. Best approach here is persisting business entities directly. Modern ORMs allows doing that without polluting business entity with attributes or forcing it inheriting some data-access specific class.
If you really want to have data mapping logic in repository, then make it private (actually only repository should require conversion of business entity to some data-access object) and don't care how this logic is implemented. Let it be part of internal class implementation. You should care only about repository being able to accept or return filled business entities - that's the responsibility of repository. It doesn't matter how mapping is implemented in repository. You should test what repository does, instead of how. So just check that expected business objects are returned by repository.
I just need to know how to verify that a method in the class being tested is called (not a dependency).
But do you really need to do that? If your GetEntity method operates correctly, do you really care how it operates? Do you really care if it performs its function by delegating to ConvertToBusiness, or by some other means?
I recommend instead that you
Think of each method as having a specification.
That specification describes what the outputs and publicly visible manipulations it must make. That do not describe how a method performs its function; that is an implementation detail that could change.
Your unit tests check only that your methods conform to their specification.
You might nevertheless use your knowledge about the implementation to choose good test cases.
But, you might declare, if I do that I am not unit testing my method code; my test of GetEntity depends on both the GetEntity method and the ConvertToBusiness method: two units, so an integration test rather than a unit test. But do you mock the methods of the runtime environment? Of course not. The line between unit and integration testing is not so clear.
More philosophically, you can not create good mock objects in many cases. The reason is that, for most methods, the manner in which an object delegates to associated objects is undefined. Whether it does delegate, and how, is left by the specification as an implementation detail. The only requirement is that, on delegating, the method satisfies the preconditions of its delegate. In such a situation, only a fully functional (non-mock) delegate will do. If the real object checks its preconditions, failure to satisfy a precondition on delegating will cause a test failure. And debugging that test failure will be easy.

Editing T4 poco template to implement custom interface

I am using the Poco generator with EF4 and I am wondering if it is possible to edit the T4 template to force all of my entity classes to implement a custom interface. Since the pocos get blown away and recreated each time the custom tool is run, I would have to add this upon each update - I would sure like to avoid that.
I realize I could create partial classes for each poco and implement the interface there, but I was hoping to avoid all that boilerplate code.
Any suggestions would be welcome.
I think I am getting closer to a solution. I am editing the tt template by adding the implemenatation to the signature that is generated.
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#> : IEntity<#=code.StringBefore(" , ", code.Escape(entity.BaseType))#>
But I have hit a bit of a snag. Some of my entities have base classes (table inheritance) that I designated in the edmx design. I have need to force all the entities to implement an interface called IEntity. The IEntity contract has no methods so there really is nothing to implement. I will need to rely on all of the entities having a common base. This is due to a completely separate implementation of a custom validation framework. I am getting the proper signatures for most of the entities, however, the entities that already have a base class are throwing a wobbly because you cant implement an interface before you inherit a base class. :IEntity, BaseClass is not allowed. I need to swap those but am not sure how I would pull that off in the template.
On perusing the code in the CodeGenerationTools class that the T4 template uses (found in the include file EF.Utility.CS.ttinclude), I came across this function StringAfter(string value, string append). Therefore, the answer is quite simple, since you state all your entities have to implement IEntity, the following should do the trick:
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#> : <#=code.StringAfter(code.Escape(entity.BaseType), "," )#> IEntity
In fact, I know it does because I've tested it :-)
After the T4 template is added to your application, it becomes part of your app and as any other part of the app, you can do whatever you want with it. If for some reason, you don't want to modify the VS added template, make a copy of it and update this to include only the interface implementation. The second way would produce another set of partial files with the custom interface being implemented.
Dont know if this is near what you need but....
I´ve created a Nuget Package that scaffold tiers from T4-templates.
There are default templates for all interfaces (Repository Pattern and UnitOfWork), but you can edit these templates yourself and re-scaffold your system.
To keep it short.. You just install the package (Install-Package CodePlanner) and then define your domainmodel.. And then run "Scaffold CodePlanner.ScaffoldAll"
Its open source (codeplanner.codeplex.com)
Demo: http://average-uffe.blogspot.com/2011/11/codeplanner-011-released-on-nuget-and.html
Edit: The codeplanner package is built for MVC3!
Regards
Uffe