I'm a little confused about the concept of services.
Let's assume i want to create a new user.
Right now, i'm checking if all fields are non-empty in Model (project.Web solution) and in UserServices too (project.Services solution). But to validate the email address i have to create a new function.
Should i create that class in project.Services, something like GeneralValidation.cs and use it, or should i separate it from the Services and create a new project?
Until now i didn't create two solutions for Repositories and Services. I just had one solution for testing, other for project.Web, and another solution where i had the a domain folder, repository folder, and a few classes for business logic, but after reading a little about design patterns i've decided to split this.
Maybe i haven't understand yet the meaning of Services. For me, a service is a layer that will consume a repository (like user), and the service layer is where i should do the validation. If this is correct, that's why i don't know where to create the function for email validation for example.
If someone could explain me this i would really be appreciated. I've already read blogs articles, and search similar questions in stackoverflow but i can't be sure if i've really understand it.
Thanks
Services and Repositories are 'first class citizens' in Domain Driven Design, so I do not see why you'd want to put them in a separate project ?
For your specific scenario, why don't you create a 'UserService' which has a method 'CreateUser', which looks for instance like this:
public static class UserService
{
public static CreateUser( User u )
{
var userRepository = RepositoryFactory.CreateUserRepository();
userRepository.Save (u);
SendActivationMailForUser(u);
}
private static void SendActivationMailForUser( User user )
{
....
}
}
Some more information about services can be found here
Related
I have a CFML ColdBox framework model service which needs to build links. However, models don't have access to the framework SuperType thus don't have access to event.buildLink().
How can I give services within my model the ability to create links? Is there a way to make the buildLink() functionality available through some kind of dependency injection?
Sample model service:
component
singleton
{
function getLinkToUser( required numeric userId ) {
return event.buildLink( "users.#arguments.usersId#" );
}
}
--Update--
Many of the comments suggest that embedding framework functionality into the model may be a mistake, and that buildLink() should really only be used within views. For the most part, I agree, and feel introducing framework services into the model violates encapsulation and concerns.
That being said, let's expand the above code example to a more real-world situation:
Let's say you have a model service which generates emails to customers and the content of those emails is very much determined by complex business rules. In this case, I could see an argument for generating the email content in the model because that is where business rules live.
If you instead generate the email content in the view, you would be executing business logic into a layer which should really only be used for display/output.
Assuming that generating the email body text in the model layer is the right thing to do, doesn't it also make sense that it should also be able to build HTML links based on framework routes within those emails there as well?
I recommend using something like CBMailService and then in the send mail you would render the layout/view, and inside of those, you have access to the event to be able to buildLinks.
You can pass in bodyTokens for variables, into the views, and it will handle the rendering for you.
Hope this helps.
var mail = mailservice.newMail(
to = arguments.recipients,
from = '"Do not reply" <postmaster#noreply>',
subject = arguments.emailSubject,
bodyTokens = bodyTokens,
type = 'html',
additionalInfo = { categories: categories }
);
mail.setBody(
renderer.get()
.renderLayout(
view = "/modules/core/views/email/emailSigninSheet",
layout = "/modules/core/layouts/email"
)
);
I just recently read about "Mocking objects" for unit testing and currently I'm having a difficulties implementing this approach in my application. Please let me explain my problem.
I have a User model class, which is dependent on 2 data sources (database and facebook web service). The controller class simply use this User model as an interface to access data and it doesn't care about where the data came from.
Currently I never done any unit test to this User model because it is dependent on an external web service. But just a while ago, I read about object mocking and now I know that it is a common approach to unit test a class that depends on external resources (like in my case).
Now I want to create a unit test for the User model, but then I encountered a design issue:
In order for the User model to use a mocked Facebook SDK, I have to inject this mocked Facebook SDK to the User object (probably using a setter). Therefore I can't construct the Facebook SDK inside the User object. I have to construct it outside the User object, and inject the SDK into the User object.
The real client of my User model is the application's controller. Therefore I have to construct the Facebook SDK inside the controller and inject it to the user object. Well, this is a problem because I want my controller to be as clean as possible. I want my controller to be ignorant about the application's data source.
I'm not good at explaining something systematically, so you'll probably sleeping before reading this last paragraph. But anyway, I want to ask if anyone here ever encountered the same problem as mine? How do you solve this problem?
Regards,
Andree
P.S: I'm using Zend framework, PHP 5.3.
One way to solve this problem is to create two constructors in User: the default one instantiates the real-life data sources, the other one gets them as parameters. This way your controller can use the default constructor, while your tests use the parameterized one to pass in mock data sources.
Since you haven't specified your language, I show you an example in Java, hopefully this helps get the idea:
class User {
private DataBase database;
private WebService webService;
// default constructor
public User() {
database = new OracleDataBase();
webService = new FacebookWebService();
}
// constructor for unit testing
public User(DataBase database, WebService webService) {
this.database = database;
this.webService = webService;
}
}
This isn't really a question about mocking, but about dependencies--and trying to unit test has forced the issue. It sounds like currently you create your User object within your Controller.
If the User and Controller have the same lifetime (they're created at the same time), then you can pass the User into the Controller's constructor, which is where you can make the substitution.
If there is a User object per call, then perhaps the User object should be passed in by the environment, or returned from some Context object.
If you make the Facebook SDK Object(s) publicly accessible, your User object can still create it when it sets up but you can replace it with a mock before you actually do anything on the User object.
[Test]
public void Test()
{
User u = new User(); // let's say that the object on User gets created in the ctor
u.FacebookObj = new DynamicMock(typeof(FacebookSDK)).MockInstance;
Assert.That(u.Method(), Does.Stuff, "u.Method didn't do stuff");
}
You don't say what language you are using, but I use Ruby and Mocha for mocking objects, and it's quite easy.
See http://mocha.rubyforge.org/.
here the fourth example shows that any call to Product.name from the unit under test is intercepted and the value 'stubbed_name' is returned.
I guess there are similar mechanisms in Java, etc.
Since you will be Unit Testing your test class will play the role of the Controller, so that one should not be touched. So that can remain clean.
You are well underway of reinventing Dependency Injection. So it may be worthwhile to look at Spring or Guice to help you with the plumbing. (If you are in Java land).
Your test can indeed do the injection of the Mocked Facebook SDK and your Database service using setter or constructor arguments.
your tests will now do what the controllers (and maybe views) will do and verify the proper routines are called in the SDK's and that the resources are properly obtained and disposed of.
I have been implementing a new project which I have decided to use the repository pattern and Entity Framework.
I have sucessfuly implemented basic CRUD methods and I have no moved onto my DeepLoads.
From all the examples and documentation I can find to do this I need to call something like this:
public Foo DeepLoadFoo()
{
return (from foobah in Context.Items.Include("bah").Include("foo").Include("foofoo") select foo).Single();
}
This doesnt work for me, maybe I am trying to be too lazy but what I would like to achieve would be something along the lines of this:
public Foo DeepLoadFoo(Foo entity, Type[] childTypes)
{
return (from foobah in Context.Items.Include(childTypes).Single();
}
Is anything like this possible, or am I stuck with include.include.include.include?
Thanks
This blog post mentions that the Entity Framework ObjectContext has all the metadata about entities and their properties. So maybe you can use that metadata to walk the properties of your entity, and their child properties, etc.
In other words, I believe you should be able to use the metadata to automatically compose Include calls on your query.
I'm after some guidance on how to approach coding a problem, I don't want to jump straight into coding without think about it as I need it to be as generic and customisable as possible,
The scenario is i have a web service that acts as a gateway to downstream services, with the aim of authenticating and authorising SOAP message destined for down stream services, basically allivating the downstream service from doing it themselves. Each SOAP message has a variety of different WS-Security mechanisms attached usually a WS-UsernameToken, WS-Timestamp, and a XML Signature of the message body.
My problem is i want to figure out a good extensible way of validating all these security mechanims, I'm not after how to do it just how to appraoch it.
I thought about having a controller class that is intialised and controls the validation flow i.e.
ISecurityController controller = SecurityControllerFacotry.getInstance();
boolean proceed = controller.Validate(soapMessage);
using it very much like a template design pattern which ditates the flow of logic i.e.
public Boolean Validate(Message soapMessage)
{
return ValidateAuthentication(soapMessage) && ValidateTimeStamp(soapMessage) && ValidateSignture(soapMessage);
}
Would this be the best apporach to the problem?
Also would it be best to put these validation methods each into a class of there own that which implemented a common interface? So that a class could be instantiated and retrieved from some sort of validation factory i.e.
IValidationMechanism val = ValidationFactory.getValidationType(ValidationFactory.UsernameToken);
boolean result = val.Validate(soapMessage);
This would give me an an easily extensible aspect.
Would this be an vaible solution or can anyone think of other ways of doing it?
I'm interset in design patterns and good oo principles so would like to go down a route utilising them if possible.
Thanks in advance
Jon
EDIT: The service is basically a gateway security service that relieves the burden of authentication and authorisation from services that sit behind it. The security service can be thought of as an implicitly invoke intermediary on the SOAP message path that validates the security mechanisms in the SOAP message and depending on the validation result forwards the message to the appropriate down stream service by interrogating the WS-addressing headers. Although the service is not really the question it is more on how to implement the validation procedure.
I think your intuition on this is good; go with the single interface approach. That is, hide your validation implementations behind a single validation interface; this allows you to extend your validation implementations later without modifying the calling code.
And yes, the idea of putting the validation into its own class is a good one; you might want to think about having a common base class, if you have any common validation items (for example, username might be a common validation element, even though each different validation scheme may encode it differently; one as an element, another as an attribute, etc.). I think validation classes is a more appropriate mapping for the level of complexity that you're talking about anyhow, as opposed to validation methods; I suspect that the type of validation you're doing requires groups of methods (i.e., classes).
I can think of another way to validate your SOAP message against different validations. You use a visitor Pattern.
For that You will have a simple wrapper around the SOAP message you get.
MySoapMessage{
SOAPMessage soapMessage;
List<String> validatonErrors;
void accept(Validator validator){
validator.isValid(this);
}
}
Your security Controller will contain the list of Validatiors which you will inject basically.
SecurityController{
List<IValidator> validators;
//Validate the message
void validate(MySOAPMessage soapMessage){
forEach(Validator validator: validators){
soapMessage.isValid(validator)
}
}
}
Your Validators will look something like this.
UserNameValidator implements IValidator{
public void validate(MySOAPMessage message){
// Validate and put error if any
}
}
You dont need and unnecessary factory here for the validators.. if you want to want to add/remove validators from the controller you just inject/un inject then from the list.
Spring has a generic validation package that handles this type of process nicely IMHO.
Theirs looks something like
public interface Validator {
public boolean supports(Class<?> clazz);
public void validate(Object o, Errors errors);
}
Granted, they're using an Errors param to return validation issues in, which might or might not suit your goal.
I'm new to the Repository Pattern and after doing a lot of reading on the web I have a rough understanding of what is going on, but there seems to be a conflict of ideas.
One is what the IRepository should return.
I would like to deal in ONLY Pocos so I would have an IRepository implementation for every aggregate root, like so:
public class OrangeRepository: IOrangeRepository
{
public Orange GetOrange(IOrangeCriteria criteria);
}
where IOrangeCriteria takes a number of arguments specific to finding an Orange.
The other thing I have is a number of data back-ends - this is why I got into this pattern in the first place. I imagine I will have an implementation for each, e.g
OrangeRepositoryOracle, OrangeRepositorySQL, OrangeRepositoryMock etc
I would like to keep it open so that I could use EF or NHibernate - again if my IOrangeRepository deals in POCOs then I would encapsulate this within the Repository itself, by implementing a OrangeRepositoryNHibernate etc.
Am I on the right lines?
Thanks
EDIT: Thanks for the feedback, I don't have anyone else to bounce these ideas off at the moment so it is appreciated!
Yes, your version is the safest / most compatible one. You can still use it with about any resources, not only data access ones, but with web services, files, whatever.
Note that with the IQueryable version you still get to work based on your POCOs classes, but you are tied to the IQueryable. Also consider that you could be having code that uses the IQueryable and then turns out it you hit a case where one of the repository's ORM doesn't handle it well.
I use the same pattern as you do. I like it a lot. You can get your data from any resources.
But the advantage of using IQuerable is that you do not have to code your own criteria API like the OrangeCriteria.
When NHibernate gets full Linq support then I may switch to the IQueryable.
Then you get
public class OrangeRepository: IOrangeRepository {
public IQueryable<Orange> GetOranges();
}