In my company we have developped some applications. We have to create an API for one application (say application A), so that the others can use it (an its data).
The question is : we already have developped PHP classes for the model of Application A, if we want to create an API, should we :
- re-use these classes (too much functionnalities for an API, too heavy...)
- create one PHP class, with some basic functions, that takes in input and returns only raw values (like strings, array... NOT complex classes)
- create another set of PHP classes, simpler, and designed only to be used by an external application (so only to get data easily)
Usually, an API is the 2nd solution (to be used as well with PHP than as a web service for example), but i find it too bad that we made a complex and usefull class modelisation, then we tear it apart just to have functions, strings and array.
The 3rd one seems to me to be the compromise, but a collegue of mine insist that this is not an API. Too bad...
What do you think ?
Solution number 3 might be the best one from an architectural point of view. Basically you are using a Facade Design Pattern to simplify your API. Since I am dealing with it at the moment: In Patterns Of Enterprise Application Architecture this approach is described as the service layer which makes totally sense since you don't want to expose any user (meaning whoever will deal with your API) to more complexity than is actually needed or desired.
This includes using the easiest possible interface and transfer objects (raw values if they make sense). As soon as your Facade is being called through remoting services (like a webservice) you will eventually have to break repsonses and requests down to raw values (data containers) anyway.
Build a set of Facade classes that simplify the public API.
Create some thin wrappers that implement simpler API over the original classes. DO NOT reimplement any business logic in the wrapper - that'd lead you into trouble if any of the logic changes, as you will surely lose track of which piece was modified and which was not. Keep the external inputs/outputs simple, if you need something more complex than string, use XML or JSON for structured data, but try to avoid too much complexity - if you have 2 things to pass two query parameters might be much better than one structure with 2 fields.
That's the 'Facade' pattern.
I would also say have a look at the Facade pattern.
Build a set of Facade classes that only offers the functionality that is really needed to be public. Those classes then for sure use your current core classes.
This gives you also the advantage that if you change the core classes, the API must not necessarily being changed.
Related
I am learning about design patterns. Currently I am working on a web service and I have time to structure the code, where I want to implement some design patterns.I already do watch to have each class doing one related thing, and write small functions with one or two parameters, but when it comes to design patterns, I am stuck.
My application is getting the data from external api, users, organizations and jobs. I have created these three classes, and currently they are all containing almost same curl call, same curl options and headers. And each of this class have one function, for organizations - getOrganizations, for users - getUsers ... Which all have same body, just a different curl call.
So I need just a reference, to a design patterns that can help me structure maintainable code.
From reading your description you just need to practice OOP a bit more. (object oriented programming).
In this given example you could make a function that accepts the URL and either make all your requests extend from that base class that has that function 9r make a utility class with the curl logic and simply use that.
Also there are a ton of good php curl plugins on composer which can help you.
I have, within a SaaS app, an abstract class with ~12 extensions totaling ~60 methods, thus making this abstraction quite valuable.
However, these methods must now reference client-specific and db-housed API Keys, as we aim to integrate with a particular CRM that requires this dynamic data. This makes instances ideal, but at the cost of the abstraction.
No longer can we statically store these keys for use with user sessions and crons.
Without doing something as seemingly sloppy as manually setting server variables (notice my desperation), how would you architect this?
P.S. Before something is said, I've referenced SO enough to appreciate the value of code examples, but didn't see an application here.
Thank you.
i got a little bit confused about decoupling, separating of concerns, the framework (Symfony2) and my business model. Let me explain :)
In modern web based projects we're supposed to have a thin controller. This seems to be best practice nowadays. Also it seems to be best practice to decouple the framework and the business model. And to do separation of concerns. I'm fine with all of that. Using events/event dispatching works like a charme to solve these concerns.
But now i have a task where i need to do the following things:
read a cookie
save some data to the database based on the contents of the cookie
delete the cookie
First my understanding of working with cookies in Symfony2:
I read the cookie using the request object
I manipulate the cookie using the response object
I should avoid using \setCookie directly
And that's the point where i got confused. Because:
I would assume that all of the three steps are part of my "task" i need to perform. So it would make sense to do all of the stuff in the same class/piece of business model.
I want to avoid mixing up my business model and third party components (like the request/response) as much as possible.
Now i have two options - But both of them are feeling wrong in some way:
Being strict on decoupling framework and business model - Reading/writing the cookie will be left in the controller, since framework components are involved. The persisting is done in the business model. - BUT: Not all the code belonging to the task are in one place now.
I also could have all of the code necessary to perform the task in one place. But then i would need to make the request and the response available within my service, which i try to avoid.
How do you guys handle this kind of issues ?
Thanks,
Stephan
I suppose that you have to make a choice: if you're trying to avoid injection of the request into a service you have to manipulate it into the controller directly.
Of course you could use a private controller that you can call from an arbitrary action and where you can store all the code: that way you could follow the DRY methodology that is always a good practice and you'll avoid injection.
In my vision of symfony however, I would use a service with injection keeping controllers small and not heavy. In that service you could store all business logic related to controller's object manipulation.
This answer, however, could vary from devel to devel so it's hard to find the right methodology
Regarding decoupling from the framework, I wrote a blog post about that here http://thesolidphp.com/decoupling-application-from-framework/
You could separate the cookie handling by creating your own class that will use the Symfony cookie manager. That class should implement an interface like CookieStorage. Your domain objects will only depend on that interface. A concrete implementation could be SymfonyCookieStorage, that will call the Symfony cookie handling objects. Now your business objects are separated from the Symfony cookie manager.
It's the same concept I wrote about in the blog post. That way you could decouple basically everything and keep you objects unaware they are using Symfony.
I was asked to do a project in PHP and to make sure it was object oriented. I've done OO and I've done PHP, but never both.
The main benefit of OO PHP (outside of inheritance/polymorphism) seems to be code organization. That's fine; I'm doing that. But where I get stuck is if I should actually be creating instances for every "object."
To me (and maybe I'm being naive here), a web app is all about making very short, stateless requests to alter or retrieve records in a database. The objects can't persist between requests. So it feels rather pointless to load data from the database, construct an object from that data, make a small update, save the data from the object back to the database, and then throw the object away. The loading/saving code seems to be a lot of work for nothing. [clarification: a waste of development time, not processing time... not too concerned about overhead]
The alternative is to have a bunch of singletons (or classes with static methods) that just provide a nice, organized abstraction layer to the database layer. I guess writing code in this manner just doesn't feel truly OO. Am I missing something or is that style fine?
Yes, you could summarise the benefits of OO as "code organization"; but this is true for all languages (not just PHP). In reality, it's more than that; it's about how you think about your data structures and algorithms, i.e. about how they map to concepts in the problem domain, how they relate to one another (ownership, parent-child, polymorphism, etc.), and how they expose clean, consistent interfaces to one another (encapsulation). If these concepts would benefit your application, and outweigh the extra development time vs. a quick-and-hacky procedural solution, then go for it.
I don't think persistence has anything to do with it.
I think you should question why you've been asked "to make sure it was OO". This seems like a pretty arbitrary request without further justification. Normally, the approach should be to write your application in the style that best suits the requirements, not arbitrary whims...
Singletons are essentially just global variables with some namespace sugar added in. There are a few main benefits to programming with objects and classes that you just don't get from straight procedural programming. One is inheritance, as you mentioned. Another is the namespacing - you can have a code to compress the lot into a single include file (more meaningful in interpreted languages like PHP than in compiled languages).
Objects are essentially a collection of functions with a shared state (though singletons make that a global state. Beware.) As you pointed out the benefit is mostly that that state is transparently shared by the functions without needing to explicitly pass it every single call. If you have various functions per request operating on shared data and wish them to be specialized forms of a general set of functions, OOP is probably a good fit.
Since you have been tasked to "make sure it is object oriented", I'd take some time to consider common groups of functions, generalizations of same, etc.
In the end the setup/teardown time of the objects isn't too bad - and it might even save some development time in the future if you do a good job.
I think OOP is just a programming style and has nothing to do with developing an application. What you need is a pattern that provides a sufficient abstraction layer (for example: MVC).
My recommendation is: Fat-Free.
It's tiny, simple and quickly take you to the minimal viable version of your product. It has everything that you might need (Caching, ORM, CRUD, Captcha...) and is so flexible that you can use any pattern and with your custom directories hierarchy.
Check out the extensive documentation. The only issue is that it requires PHP 5.3. I think it's reasonable considering the options and flexibility it offers. It really changes the way you work; you should definitively give it a shot.
Like most things in life answer is somewhere in a middle.
Todays application use ORMs (for example doctrine for php) for different kind of optimization, better understanding of database approach (which is important for larger dev teams), easier update of the code, abbstraction layer that is well known to people who join the project, caching mechanisms,....
Classes with static methods are just fine if you are doing some smaller project on your own, but when more people are involved in progress you simply need something more robust and standardized.
I have learned how to use classes in PHP and so far I have only really found one useful application for them. I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect.
Aside from this example, what are some other useful ways to utilize classes in a practical sense?
I use a database class all the time.
Here are a couple examples:
http://www.massless.org/_tests/phpdb/
http://slaout.linux62.org/php/index.html
http://www.tonymarston.net/php-mysql/databaseobjects.html
It's a really good idea to read other people's code and see how they have separated things into classes. Look at some PEAR modules or a framework ( Zend, Symfony, Cake ).
Any time you can define a 'thing' that 'does stuff', you've got a candidate for defining an object. Two concrete examples, from the PHP standard library, that immediately pop to mind are :
Numerous database modules use objects for connections, queries & results.
The DateTime class encapsulates a generic concept of time with input & output formatting, timezone conversions & date arithmetic.
The thing is, Object Oriented Programming is a big idea - you can solve almost any programming problem in an object oriented way.
I've built an utility class that humanizes the use of the mail() function, which I tend to use quite a lot.
By using classes (e.g. PEAR packages mentioned above, others), you are able to leverage code that has already been written and tested to perform common tasks.
Helps you to not reinvent the wheel, too.
I would highly recommend learning about [design patterns][1]. Many of them make good use of classes and solve common programming problems. In particular the Factory and Abstract Factory patterns are a good place to start.
There is also an excellent book called PHP Hacks that has a chapter about implementing a host of different patterns in PHP, so you might want to check that out.
Also, explore some of these built-in objects in PHP to see how they work and get more ideas:
PDO
ArrayObject
SimpleXMLElement
DirectoryIterator
[1]: http://en.wikipedia.org/wiki/Design_pattern_(computer_science)"design patterns"
I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect.
Check out http://en.wikipedia.org/wiki/Cohesion_(computer_science)
Your example sounds like Logical cohesion.
Aim for functional cohesion. Each class does a particular task, and make classes as generic as possible and you'll find you can reuse them over and over.
A great example of that, is Symfony's sfParameterHolder:
http://www.symfony-project.org/book/1_2/02-Exploring-Symfony-s-Code#chapter_02_sub_parameter_holders
Symfony uses it to hold variables for view templates (in a MVC), to store request parameters in the web request object (itself a class that represents all request parameters dutifully stripped of backslashes etc), in the sfUser class to store all the parameters that eventually go in the $_SESSION etc etc.
Download Symfony's "sandbox", go into the /lib/symfony/ folder and learn from it. It"s complex but the code imho is very clean.
http://www.symfony-project.org/installation
Zend is nice too, but the number of include files mayb be overwhelming and I am personally not fond of their naming conventions, in particular using underscore prefixes.