OOP design - validation when validation means hitting the database to check - oop

Let's pretend we're talking about an HTML complaint form, one field of which is a product list from the company catalog.
I gather that validation usually (always?) goes in its own class.
I also gather that it's good practice to have gateway classes which can handle all the database queries internally, so when I save my complaint from my complaint form I don't have to worry about the database details.
But what about validation that requires accessing the database - for example checking that the product is actually a product we have (and not someone tampering with the form). This can only be done by finding a match in the database... but my database is abstracted behind my gateway.
Do I add validation logic to my gateway? Do I create validator gateway classes? Do I empower my validator with database logic?
EDIT - attempt to clarify...
customer clicks link to complaint form
HTML complaint form is built with a <select><item></item></select> dropdown with X products from our fictional company catalog
Customer completes form and Submits // Wiseguy alters HTML so product is "Schweddy Balls" and submits
Form class validates simple things like date, all required fields have data, email address, etc.
at step 4, in order to validate that the product being complained about is legit, you'd have to hit the database's product table to see if it's still a valid datapoint. Should that logic go in the form class, the gateway class, or somewhere else? putting it in the form class breeds dependencies, does it not?

Validation should, oddly enough, not be done directly through a Validation class. A model object's class (in this case probably Complaint) should include the Validation class and the validations should be done in there. Since the Complaint has access to all Complaints, validation methods can use the methods of the Complaint class, or call another model class if needed.
When you say "gateway" to the database, I believe you're talking about on Object Relational Mapping (ORM), which allows model objects, like a Complaint, to abstractly talk to the database. The ORM should have no knowledge of the structure or specifics of the application, it should only be an abstract API for objects to communicate to the database or other backend.
Surely my response does not cover everything, so further questions/clarifications welcome.

It's usually good practice to store valid data, only. So, one necessarily writes a validator on the server-side to ensure that requests are valid and only valid data gets put into the database, and as an optimization one typically validates on the client side (e.g. in JavaScript) so that the user is informed of invalid input without needing to submit the form and without needing to make a roundtrip. Doing the validation as part of the database write, allows subsequent reads to be done trivially with no checks.
I don't know the specifics of what counts as "valid" for you, but you can probably save a lot of database lookups with caching. Perhaps you could give some more information about your requirements?

Related

RESTfully creating object graphs

I'm trying to wrap my head around how to design a RESTful API for creating object graphs. For example, think of an eCommerce API, where resources have the following relationships:
Order (the main object)
Has-many Addresses
Has-many Order Line items (what does the order consist of)
Has-many Payments
Has-many Contact Info
The Order resource usually makes sense along with it's associations. In isolation, it's just a dumb container with no business significance. However, each of the associated objects has a life of it's own and may need to be manipulated independently, eg. editing the shipping address of an order, changing the contact info against an order, removing a line-item from an order after it has been placed, etc.
There are two options for designing the API:
The Order API endpoint intelligently creates itself AND its associated resources by processing "nested resource" in the content sent to POST /orders
The Order resource only creates itself and the client has to make follow-up POST requests to newly created endpoints, like POST /orders/123/addresses, PUT /orders/123/line-items/987, etc.
While the second option is simpler to implement at the server-side, it makes the client do extra work for 80% of the use-cases.
The first option has the following open questions:
How does one communicate the URL for the newly created resource? The Location header can communicate only one URL, however the server would've potentially created multiple resources.
How does one deal with errors? What if one of the associons has an error? Do we reject the entire object graph? How is that error communicated to the client?
What's the RESTful + pragmatic way of dealing with this?
How I handle this is the first way. You should not assume that a client will make all the requests it needs to. Create all the entities on the one request.
Depending on your use case you may also want to enforce an 'all-or-nothing' approach in creating the entities; ie, if something falls, everything rolls back. You can do this by using a transaction on your database (which you also can't do if everything is done through separate requests). Determining if this is the behavior you want is very specific to your situation. For instance, if you are creating an order statement you may which to employ this (you dont want to create an order that's missing items), however if you are uploading photos it may be fine.
For returning the links to the client, I always return a JSON object. You could easily populate this object with links to each of the resources created. This way the client can determine how to behave after a successful post.
Both options can be implemented RESTful. You ask:
How does one communicate the URL for the newly created resource? The Location header can communicate only one URL, however the server would've potentially created multiple resources.
This would be done the same way you communicate linkss to other Resources in the GET case. Use link elements or what ever your method is to embed the URL of a Resource into a Representation.

designing a restful api: naming URIs, custom headers?

EDIT: I've solved my issues (for now at least).
I've recently been working with the Zendesk REST Api and their use of the custom "X-On-Behalf-Of" header for looking up tickets opened by a particular user got me thinking about Restful Api design choices (in no specific language, more of a how to name URIs question). I've also read this related question on Custom HTTP headers, but it left me with more questions than answers.
Say I have an example restful web service dealing with rental apartment applications where clients use Basic Auth (keep it simple) to authenticate. Define the basic data as such:
Users (can be of type landlord or renter)
Forms (which consist of one or more Document resources and some form meta data like form name and version info)
And then some type of resource corresponding to Rental Applications, which ties together Forms, Applicants (one or more renters), Landlord, and some metadata like status and dates.
I'm struggling to properly model the URIs for the Applications resource in general, and more specifically with respect to a clients role. (assume api root is https://api.example.com/)
How do I allow a Landlord to fetch a list of applications sent to them? My intuition says make a request to "GET /applications" and Basic Auth lets the server know which user to build the list for; likewise "GET /applications" requested by a Renter would return a list of applications they've sent...but I'm not confident this is a solid design in general to mix and match sender vs. recipient lists at the same URI. Should I be thinking about the "/applications" resource differently, and perhaps allowing a hierarchy like "/applications/[USER_IDENTIFIER]" for each user instead?
Also, regardless of my applications URI design, assume a Landlord is able to create an application on behalf of a renter. Is this better accomplished by sending a custom header like "X-Create-On-Behalf-Of: somerenter#example.com" with the PUT/POST creation request? Or should my schema define a field which allows for this alternative scenario.
I'm very much an amateur at this, so I'm open to any criticism of my assumptions/design, as well as any pointers for learning more about designing RESTful api's. Thanks for reading.
I think I've found a solution.
Landlords and Renters are really just subclasses of the same object, which I'll call Party (as in party to a transaction, not birthday party). So then each one has their own resource, named like /party/PARTY_ID.
It's easy to extend this to see that /party/SOME_LANDLORD/applications and /party/SOME_RENTER/applications solve my issues. It also removes my need to consider custom headers.

How to separate the responsibility in application?

For example,
I want to separate the online shop into three parts.
User: the user related information, for example, they login. logout.
Communication: sending email, or newsletter modules.
ShoppingCart: displaying order.
Ok, these three module is the main function of of my little online store.
Clearly, the user medule, deal with its own stuff, for example, user change their profile pic(ok, I think it is non-sense to have a profile pic for user, just think it is an example.)
user ---call---> user
But I got a problem here, is when the user doing some functions, which require cross-module call....
Let me give a example, if the user lost the password, the user needs to use the communication method to send a new password to him/her...The situation will become somethings like that:
user ----call---> communication
A worse situation is use all the modules, here is the situation:
The user using a shopping chart to deal with his/her shopping, after that, he /she make the order, and a invoice use communication modules to send to the user.
user ----call---> shoppingCart ---call---> Communication
Therefore, each module is not separate, all modules knows each others.... But I don't want to do that, for example, this time I am doing a new application, for example, I doing a video sharing web site which only use "user" and "communication", I don't really need the "shoppingChart. ", and having a new video module.....
It is ok for me "upgrade" my user and communication method to deal with the video module, but the question is, if I got something bugs fix, for example, the getFullName method is doing something wrong, when I need to "upgrade" back the online shop application, I need to take the "video" module too.....
What I wanna to ask is, how to separate their responsibility, and how to make the code more reusable? Thank you.
It is good practice to minimize the coupling in your application, but removing it entirely is not always possible.
My recommendation would be to build base classes User, Communication, and ShoppingCart that provide only basic interfaces, such as getFullName()
Then, for each application, write separate wrappers that are able to interact with your base classes. You may have an OnlineShopping class and a VideoSharing class, that contain the functions you need that are specific for each application.
There are a number of structural patterns that may help you out with your design. Also, take advantage of inheritance for functionality that is similar across all applications.

How to associate calculated values to an object

I have some basic objects like Customer, Portfolio and ... with some association to other objects. I can easily display the required information in the web page by reading object values. The problem is that what do I do when the value associated with the object is calculated and returned by a method, a value that makes sense only in certain context and cannot be attached to the object as an instance variable? In this case if I have a list of say Users I have to pass the username of each user to the method to get the calculated value. This causes problem to keep the association while displaying the values in the page.
An example to make this clear:
An application provides the functionality for users to keep track of each others activities by letting them add whoever they want to a list. If this user performs a search on users there's the option to follow each returned user. I want to make sure this option is disabled for those user's that are already being followed. This functionality is provided by a method like isFollowed(String follower, String followee) which returnes a boolean. How can I associate this boolean values to each user in search result?
Solutions:
One thing I can think of is to add a followed instance variable to User class. But I don't think it's a good approach because this variable only makes sense in a certain context. It's not a part of User class in the domain.
The other way I can think of is to use Decoration or Wrappers in a way to extend the User class and add the attribute in the child class. But again what if I have several objects that need to be in the same context. In that case I have to extend all of them with the same boolean attribute in all classes.
I hope I could make it clear.
In principle, I don't see anything wrong with instance method on User: bool IsFollowedBy(User user).
Of course, this could lead to performance issues. If that is the case, you can create separate object for presentation purposes which bundles data from User and whether he is being followed by the user performing search. Then you can build query which retrieves all necessary data for such object in a single roundtrip to DB.
One solution is to avoid querying Entities (as in DDD/ORM) and query directly using subquery/join or even using some denormalized database. This is something CQRS pattern suggests.
Other solution is to do computations on application layer (how many Users can you show on the same page anyway), which is expensive but you can implement some caching techniques to make things easier.

CakePHP: model-based permissions?

Struggling with a decision on how best to handle Client-level authentication with the following model hierarchy:
Client -> Store -> Product (Staff, EquipmentItem, etc.)
...where Client hasMany Stores, Store hasMany Products(hasMany Staff, hasMany EquipmentItem, etc.)
I've set up a HABTM relationship between User and Client, which is straightforward and accessible through the Auth session or a static method on the User model if necessary (see afterFind description below).
Right now, I'm waffling between evaluating the results in each model's afterFind callback, checking for relationship to Client based on the model I'm querying against the Clients that the current User is a member of. i.e. if the current model is Client, check the id; if the current model is a Store, check Store.clientid, and finally if Product, get parent Store from Item.storeid and check Store.clientid accordingly.
However, to keep in line with proper MVC, I return true or false from the afterFind, and then have to check the return from the calling action -- this is ok, but I have no way I can think of to determine if the Model->find (or Model->read, etc.) is returning false because of invalid id in the find or because of Client permissions in the afterFind; it also means I'd have to modify every action as well.
The other method I've been playing with is to evaluate the request in app_controller.beforeFilter and by breaking down the request into controller/action/id, I can then query the appropriate model(s) and eval the fields against the Auth.User.clients array to determine whether User has access to the requested Client. This seems ok, but doesn't leave me any way (afaik) to handle /controller/index -- it seems logical that the index results would reflect Client membership.
Flaws in both include a lengthy list of conditional "rules" I need to break down to determine where the current model/action/id is in the context of the client. All in all, both feel a little brittle and convoluted to me.
Is there a 3rd option I'm not looking at?
This sounds like a job for Cake ACL. It is a bit of a learning curve, but once you figure it out, this method is very powerful and flexible.
Cake's ACLs (Access Control Lists) allow you to match users to controllers down to the CRUD (Create Read Update Delete) level. Why use it?
1) The code is already there for you to use. The AuthComponent already has it built in.
2) It is powerful and integrated to allow you to control permissions every action in your site.
3) You will be able to find help from other cake developers who have already used it.
4) Once you get it setup the first time, it will be much easier and faster to implement full site permissions on any other application.
Here are a few links:
http://bakery.cakephp.org/articles/view/how-to-use-acl-in-1-2-x
http://book.cakephp.org/view/171/Access-Control-Lists
http://blog.jails.fr/cakephp/index.php?post/2007/08/15/AuthComponent-and-ACL
Or you could just google for CakePHP ACL