Design pattern for building a reasonably complex PHP web service [closed] - php

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have just "finished" coding up a relatively involved web service in PHP. The code base is now a bit of a mess due to last minute requests, changes, add-ons, the usual.
I tried to code it as lightly as possible and in a manner that would maximise performance.
Therefore, I didn't use any frameworks like Zend or any ORMs like Doctrine.
I was wondering if there are any frameworks or design patterns that exist for the sole purpose of building APIs/web services in PHP?
I'm thinking of a refactor and I want to make sure now I know exactly what's involved I can build this thing properly.

I apologize in advance for the self-reference here to my own framework - there's no way for me to help you otherwise since I don't use anything else. I'm not advertising, since it's not public.
As I said in my comment, I think a good web front-end framework shouldn't mean it is a poor web service framework.
Because I was unsatisfied with the restrictive way any of the popular PHP frameworks (CodeIgniter, CakePHP, Kohana) processed requests, as well as their size, I wrote a framework that is designed for really only two purposes, process a request and determine an action to take, and then separate the code for that action from the view (response).
The design pattern I use is this:
All URLs are rewritten (mod_rewrite) and passed to your execution entry point.
Your entry point sets up paths that it will recognize and process. I.E. for a web service:
/users - User list
/user/* - User identified by the value where * is.
/user/*/delete - Delete the user
/posts - List posts
/post/* - View post *
Along with the path you specify a function, I.E. UserActions::saveUser to be executed if the HTTP method is POST. The reason it's only executed on POST is to enable output and input to have the same URL.
The path also specifies a view. This is the response body that will be sent to the browser. It can be rendered as straight PHP, or you could plug in a template engine. In the case of web services, all paths would probably use a single view that renders your data in the output format (JSON, XML, whatever). The view can be just a PHP method and is not required to specify a template file.
In the case of a web front-end, the view can have a parent view which wraps it (creating the page from the inside-out).
The last point is security. You can define a security type to be applied to any path. A security type just specifies what function (like SecurityManager::authorize) to check for authorization and if false is returned, it redirects to a path of your choosing.
The reasons I believe this design pattern works well for Web Services:
Enables you to use a single-entry point, but can be used with multiple entry points (for optimization, if needed).
No assuming that you want your URLs to match your Object Model, like most of the major frameworks do (a notable exception being Zend, as mentioned in the comments).
Easily adapted to REST (instead of just checking for POST, check for other methods too).
The removal of any HTML feels completely natural, since in this pattern the response is completely separated from processing.
This can all be done in a few classes.

Imho, every MVC-based "thing" can really help you.
If you really do not want to use anything (give a try to CakePHP!) already existing, strucutring your code following mvc can really help you to split the logic of your application on more layer, and keep it more readable and debuggable.
Of course, also with the better pattern you can write awful code, it's up to you!

I think you can use the same patterns you use by simple web applications. A restful service has different interface than a web application, but everything under that interface is the same. You can transform a restful service to a web application like so:
METHOD host/resource/data => host/resource/METHOD?data
resource is the controller, METHOD is the action.
For example:
GET http://library.com/books/123 => http://library.com/books/get?123
So you can use front controller and MVC.

A quick Google and I see
Frapi
Cake
Meditation
Code Canyon
I have never used any of these

Related

Why are dynamic frameworks like this not scalable? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've always had a thing for dynamic code. Code that's really easy to add cool new features to, without doing much work. For that reason, I build lots of dynamic frameworks and use them in my projects. Some are small, some are big.
As an example, I built a small custom error reporting framework that I still use in almost all of my projects today.
Here's a quick example of how it works:
error_reportLibrary.php - This is where all the magic happens. The class and all the methods sits here. This is the file included when the framework is needed.
error_reportConfig.php - This is where my configuration goes (error types, ect). Here's an example of this file, which shall give you a pretty good explanation of how the small framework works:
(the comments in the code should explain what each element does as a setting)
# ------ Main Settings ---------
$error_handlingSettings['errorStat']=true;//set this to false, and I wont display any errors. I don't care what the other errorTypes have to say.
$error_handlingSettings['default_highlight_color']="red";//this is the default highlight color that will be used if no color is defined for a specific errorType
# ------ Open API -------
$error_handlingSettings['open_api']['status']=true;//set this to true and I'll show errors for the Open API
$error_handlingSettings['open_api']['highlight_color']="#0ff";//shall I highlight any errors that occur for this specific type? if so, set this to a color.
$error_handlingSettings['open_api']['onRemoteAddr']=true;//shall I display errors to specific IP addresses?
$error_handlingSettings['open_api']['remote_addr'][]="86.8.168.228";//so I will show to this IP
$error_handlingSettings['open_api']['remote_addr'][]="127.0.0.1";//and this IP
# ------ SQL Core -------
$error_handlingSettings['sql_core']['status']=true;//set this to true and I'll show errors for the SQL Core
$error_handlingSettings['sql_core']['highlight_color']="orange";//shall I highlight any errors that occur for this specific type? if so, set this to a color.
$error_handlingSettings['sql_core']['onRemoteAddr']=true;//shall I display errors to specific IP addresses?
$error_handlingSettings['sql_core']['remote_addr'][]="86.8.168.228";//so I will show to this IP
$error_handlingSettings['sql_core']['remote_addr'][]="127.0.0.1";//and this IP
So as you can probably tell, each error type is simply a different part of the project I'm using the framework on (for example, SQL Core is the database framework I use. So if any db query issues occur, this errorType will be looked at when printing errors).
So for printing errors, this is the syntax:
errorModule::doError("errorType","error messege");
As you can see, there are some extra little things I can do. Like display to certain IP addresses and highlight the error text, which I can confidently say: will not affect the scalability of the framework.
Remember, the above is just an example of the dynamic frameworks I create/use in my projects.
Now, to the question(almost): I've been told by a few of my colleges that dynamic frameworks like the above are terrible when it comes to scalability. Regardless of the fact that they are very maintainable. So if I used the above framework on a web app that got 1M+ requests a day, it would totally screw up...
Now I'm not apposing against their opinion (actually....) but I would like to know why this is? Why is a dynamic framework like the above considered bad for scalability?
I think you're missing the point when creating a 'dynamic framework.'
A lot of my earlier PHP code functioned sort of like this; a class with a bunch of methods and maybe a construct method that set up a state, using globals to track configuration in arrays. These all used a lot of memory compared to a wholly OOP approach; and while yes less memory and faster than an 'off the shelf' solution; nothing compared to the way I design frameworks now.
It doesn't appear you are taking advantage of things like interfaces, abstract classes, both class and interface inheritance and so forth. These types of frameworks do scale because the original code base is so small and take advantage of specific OOP functionality (like PHP 5.x's magic methods.)
Multiply a script that you felt was fast enough running on server that's not taxed very much by say 100 and, you've got problems; and you're running out of memory, hitting pages outs; and things will crawl to the point you're forced to reboot/throw more resources at the server.
Why? Poorly written procedural code that tries to act OOP, even tries to look like it, is just wrapping up old habits in a new package.
PHP is slow and clunky in general. It's high-level, which means each line carries "baggage". It's common that a single line of PHP code will convert to a slew of low-level instructions.
You can still scale 'dynamic' frameworks that rely heavily upon PHP's underlying system, and don't waste a lot of time or memory with high-level abstractions.
In my opinion, large, "convenient" frameworks often cause more problems than they solve once shit hits the fan in a production environment. My favorite teachers always reminded me to K.I.S.S. -- Keep It Simple Stupid.
Of course, If you want truly scalable performance you may want to compile your php with hiphop or write your application in a compiled language like C++ or D.

Which PHP frameworks do NOT use a front controller? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
It seems the more popular frameworks use a front controller. I understand the benefits of a front controller (reduces redundancy and simplifies extensibility), but
I want to know what PHP frameworks do NOT use a front controller. Additionally I am interested in those frameworks that use page controllers and that recommend using a real file directory structure for the urls as opposed to rewriting almost every url or using a mess of a query string. Additionally I am interested in knowing which of the frameworks that do not use a front controller implement MVC. Lastly, any additional details you can provide on the non-front-controller frameworks would be useful, particularly what version of PHP it uses or requires. (I know I can get this later information from other sites so it is not as important.)
Consider the words of Rasmus Lerdorf (the original creator of PHP):
"As for MVC, if you use it carefully, it can be useful in a web
application. Just make sure you avoid the temptation of creating a
single monolithic controller. A web application by its very nature is
a series of small discrete requests. If you send all of your requests
through a single controller on a single machine you have just defeated
this very important architecture. Discreteness gives you scalability
and modularity. You can break large problems up into a series of very
small and modular solutions and you can deploy these across as many
servers as you like. You need to tie them together to some extent most
likely through some backend datastore, but keep them as separate as
possible. This means you want your views and controllers very close to
each other and you want to keep your controllers as small as possible." - Rasmus Lerdorf
UPDATE: Many thanks to user Alex for the first of hopefully more answers. His answer is QCubed ..
"remember that front controller (index.php) and MVC are separate
patterns. That is, you can have an MVC framework that does NOT
implement or require the front controller. My framework of choice,
QCubed, happens to be like that." - Alex
Now if we can reopen this question then we can continue what we started and put together a list of frameworks that do not use a front controller. Please vote to reopen. Thank you.
I'm still learning Symfony2, so if I'm not wrong, i think you can have different front controllers. And the code would be separated in different Bundles.
By default, it has two fron controllers, one for production and the other one for development. However i think you can create more than one (one for each page)
Hope this helps
Interesting question, although I am not sure what your end game is. A controller basically 'bootstraps' the framework into a useable state. My experience lies with Symfony, Zend, and CakePHP, and can tell you that the controllers used in Symfony are quite short (~50 lines of code). However the underlying code is quite extensive, but this code does a number of things such as setup your ORM, cache heavily used arrays (creating static files in /cache directory), and initialize an autoloader for file calls, just to name a few.
Within the Symfony Framework context you have a primary controller, but you also have mini-controllers, or as you put it, page controllers, these controllers are referred to as 'actions'. An action acts as a bridge between a user request and various attributes of your application which may include file/data stores, request handling, user redirects etc. As with the primary controller the actions are meant to be lightweight, mainly consisting of API calls to underlying classes and functions.
I have actually used Zend within Symfony to fill the gaps in functionality that Symfony does not provide. So to your question, I am using Zend functionality without any controller interaction. All I need to do is initialize Zend within the autoloader (b/c Zend is correctly namespaced). Also did this with CakePHP to take advantage of the Inflector class, no controller usage, just calls to functionality I didn't want to write myself.

Do you know a good book/website about structuring your codes (PHP/ Web programming) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
i mainly use PHP and I have been coding using it for a while. My main problem with PHP is that I think as your program gets bigger, it gets harder to maintain your code (probably applies for other things). I want to reduce this complexity in maintaining/modifying my codes. I want to make things modular and have rules when to start a new class or just append to an existing class (for example). I know that there are frameworks out there (CakePHP, Symfony, Rails) but what if I just want to use my PHP and use a hybrid of my own style and an existing style for good code management?
This is not just pertaining to php, this applies to coding in general. Frameworks will only help you organize your mess but if you are new to programming a framework will only organize your messy code.
Some basic ideas to keep in mind aside from undertaking a undergraduate in computer science (which i recommend if you are serious about coding) is to make your code modular.
For example, and this is a simply example to demonstrate the point. If you have a site that generates an html table containing financial data.
(Here are a few scenarios of how to go about coding this ...)
You open up a new screen, financialdata.php, you code from line 1 to line N the code needed to get the financial data from a data source (database perhaps) and then iterate over the financial
data to construct an html table.
You open up a new screen, financialData2.php, you code a function at the top which pulls data from yuor data source and returns an object (array maybe) containing the items. You take this return value and generate your table on this financialData2.php page.
You open up yet another new screen, financialData3.php, you take your database function from financialData2.php and use it to get your financial Data from yoru source. You code another function to generate an html table based on some arguments passed in as parameters. And lastly in your financialData3.php page you display do the following and your page now has a table containing financial data from your data source.
The lesson here: the more modular your code is the better in a lot of ways. You now have a data base function that can get data, and you have a function that will render a table based on a list of items passed in.
You can now create another page and use these functions in different ways, perhaps your data source function has parameters like table and selection criteria. This way you can use the same data function to get data from different tables based on criteria. You now have a VERY basic data abstraction. (Dont let abstraction scare you aware). An abstraction is nothing more then a simplification of something. In this case we have abstracted away the details of how we get data and let our function getData take care of those details.
Please comment/ask questions and we can discuss further but honestly, I do not think one book or web site can teach programming practice like a BS in CSE can through classroom discussion and hands on practice.
Learn Design Patterns:
http://sourcemaking.com/design_patterns (covers the GOF patterns)
http://martinfowler.com/eaaCatalog/index.html (covers POEAA obviously)
Also helpful to increase code quality:
http://phpqatools.org/
A sidenote on frameworks:
while frameworks often do tell you how you should layout your code and folders and stuff, they rarely tell you how to code properly. A framework offers solutions to common problems and that's cool, but if you try to step outside of what the framework already offers in terms of functionality, you are on your own again. That is because frameworks are concrete implementations, while you want to learn about design principles.
This is about code in general (it uses Java/C/.Net for the examples if I remember correctly), but Code Complete's the best book I've read on general code structure. It covers everything, from the nuts & bolts of how to write and organise variables and methods up to program structure. I'm not sure how applicable the examples are to PHP but probably worth a look.
http://www.nettuts.com
everything you'll want to know about PHP and web development.
I like this one: http://www.wrox.com/WileyCDA/WroxTitle/Professional-PHP5.productCd-0764572822,descCd-tableOfContents.html
http://www.amazon.ca/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612
Lots of design patterns explained. But not in PHP. Good for understanding useful design patterns. Support the author by purchasing it.

How to implement service layer in Zend Framework? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm looking for some good resources to learn how to implement internal service layer in Zend Framework. This is interesting post Bookie Link, but with no concrete code samples.
Where to put service classes (/application/modules/modulename/services/?);
How to autoload them (custom autoloader?)
Most common services (user, authentication, cart, cache, feed?)
Sample implementations (any github repos?)
Good practices?
I think the answer to this question depends on your needs, your time constraints and your overall approach to/style of software development.
I have recently (A) made the decision to use Zend Framework on a small but complex web application that has a very tight deadline and (B) have spent a LOT of time investigating ORM solutions and different ZF application structures in general. The conclusion I have come to is that there isn't a one-size-fits-all solution and that you should feel free to get creative and build an application structure that you are happy with.
If you have tight time constraints and the application isn't too large, then you could just create classes with names like Application_Model_BlahService and store them in the application/models directory and they will get picked up by default by the autoloader (assuming the autoloader has been bootstrapped correctly).
But if your application is larger or if, for some other reason, you want to split classes out into more directories, you could create your own sub-directories under the application directory and use something like the code below (which would exist in your application/Bootstrap.php) to add those classes to the autoloader:
protected function _initResourceLoader()
{
$this->_resourceLoader->addResourceType( 'service', 'services', 'Service' );
$this->_resourceLoader->addResourceType( 'serviceplugin', 'services/plugins', 'Service_Plugin' );
}
You can then create classes like Application_Service_Invoice, which would reside in application/services/Invoice.php and Application_Service_Plugin_TaxPlugin, which would reside in application/services/plugins/TaxPlugin.php. (Note: the code above assumes you are using Zend_Application).
You could, in theory, take this as far as you like and separate model classes from service classes from data access classes, etc etc etc. But again, it depends on the style of development that you prefer, the size of the team and, to some degree, what requirements your persistence layer imposes on you.
One last quick thing: have a look in Zend_Application_Module_Autoloader for a list of resources that are added to the autoloader by default. (Should I have mentioned that I'm referring to ZF 1.8+ in this answer?)
You don't need hacking to get service layer work. Default autoloader has a resource namespace Service_ with services folder inside application. So, it will load service layer from application\services, classes should follow Service_* naming pattern.
Basically, you could probably put those anywhere you like ; somewhere close to the model will most likely make sense, though.
As an example, you might want to take a look to :
ZFPlanet : an example of a planet developped with ZF
Not sure it's finished, but there are several classes, controllers, models, config files, ...
Which means that going through the code can help (it has, for me, for some things)
And, especially, its application/modules/zfplanet/models/Service directory
Which contains two classes.
(Well, I hope that's the sort of thing you meant by Service, actually)

REST vs. RPC in PHP [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm building my own Ajax website, and I'm contemplating between REST and RPC.
If my server supported Servlets I'd just install persevere and end the problem, but my server doesn't support Servlets.
RPC is simpler to code (IMO) and can be written in PHP easily. All I need is a database query executer. I'm using the Dojo Toolkit and JSON.
Why should I choose REST over RPC or RPC over REST?
The best way to understand it is to read Roy T. Fielding's dissertation on it, or relevant articles on his blog where he discusses the differences between pure REST and simply RPC architectures.
Another thing to note is that the Wikipedia article on REST is in dismal condition and Fielding himself, the 'inventor' of REST, suggests that the article is inaccurate.
The biggest thing people miss with REST is discoverability - resources should include URIs for other related resources inside their hypertext, instead of relying on URI naming conventions, which are out-of-band and non-standardized.
A big problem with popular RPC implementations like SOAP or XML-RPC is that they use HTTP underneath their own proprietary architecture, rather than taking advantage of all the different properties of HTTP like PUT, GET, DELETE etc. So this doesn't fit the traditional web stack as well - a cache server in the middle doesn't work, for example, without knowing about the meaning of the contents of the RPC call.
This is an incomplete introduction to REST and RPC but I think I've highlighted some of the important points that are often missed. Be careful, since there is a LOT of wrong information out there on REST.
That said, REST is not for everything. It's an architecture, so it's rather flexible how you can implement it. But if it doesn't make sense to access things primarily as resources, then REST may not fit, or it may only fit for parts of your application, which is fine.
Uhm ... to put it simple, both are very abstract models ... so abstract, they naturally occur everywhere...
REST is the idea of having resources addressed with a global identifier (the URI in the case of HTTP) that are accessed in a CRUD way (using POST, GET, PUT and DELETE in the case of HTTP ... well, at least that's the idea)...
RPC is the idea where you call a procedure on a different machine, passing in some parameters, and taking a return value...
There is a nice short comparison on Wikipedia
Persevere creates a service, that allows both (in a very elegant way, admittedly) ... it is RESTful (although it does not only use HTTP-features to achieve this) and exposes an RPC interface...
In the end, you should look at what your application needs to do ... as most people, you'll probably wind up with an RPC API (be it based on XML or JSON or whatever), that includes a transport layer for a partially RESTful subsystem ... this is, because having RESTfulnes, means flexibility ... if the client can more or less freely traverse the data on the server (through a set of simple CRUD methods), it does not depend on a limited (problem-specific) set of methods exposed through the API, and you can shift logic clientwards...
There are three different styles of services:
RPC API - the client sends a procedure and parameters to service and the service is responsible for the executing of the command and returning a result.
Message API (Document API) - the client sends DOMs (elements), which normally are more complex structures than RPC API calls, because they tend to do not imply operations directly.
Resource API - is used for accessing resources (database tuples, files, images and etc.). In general it should also provide good Media Type Negotiation.
SOAP and REST are compilation of standards from W3C, and the main difference is that SOAP uses HTTP, SMTP and etc. as transport protocols and REST uses it as application protocol, AKA it should support (GET, PUT, PUSH, DELETE, and POST). SOAP also implies using XML and REST could use any data type (JSON, XML, HTTP, etc.). Furthermore, one of the main advantages of SOAP is the Service Descriptor (WSDL file), which gives the possibility of auto-generation of Service Connector (proxy) to the client.
There is not a silver bullet; the type and architecture of a web service are dependent on the actual client and technology requirements.
For a general idea on the subject, see one of the Martin Fowler signature books - Service Design Patterns

Categories