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)
Related
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've been coding with PHP for a while now, but I've been mainly coding with Functions and raw PHP.
I've started to think that I should be writing my code a whole lot neater and more efficiently. I still can't quite get my head around classes. Should I be writing ALL my code in classes?
For example, one of my scripts is a 'permissions manager' - which allows an admin to edit the permissions of various user groups on the site.
Traditionally, I'd have written this as just a script with functions and whatnot. But would it better to write this as a class? If so, what would this class contain? Would I have a separate permissions class for use around the site, and another for the admin-editing area?
Also the site has an API. Should this all be written as one class?
Also, should I be using public (shared) functions at all?
Thanks!
In my opinion everything depends on how large is your project. I've worked using Magento for a while and it's so big that it must be grouped in classes and packets. It's easier to read code and analyse the structure of project if it's split in classes. Also when you need to modify your project after a month or year then good structure helps to re-learn it.
It is useful to write stuff in Classes when a particular set of functions and variables belonging and/or oriented to the same entity or propose is to be used in different environments. It gives a sense of organization, delegation of tasks and avoids repetition of code.
But in situations where the above is false, it is completely disposable. Theres no point in writing a class to something that will run only in one specific place.
Also, if you only want to have a set of information organized in an object-like style like in $user->name, $user->age etc. you can simply do this:
$user = (object)array(
'name' => 'John',
'age' => 20
);
Yes, in my point of view it would be better to make your code in OOP to be more neat, understandable, readable and also for maintenance it will be more easy,
Please take a look here in this stack :
https://stackoverflow.com/questions/4409824/what-are-the-advantages-of-object-oriented-php
You should approach that question from a different angle. Don't just use OOP because you think you have to.
Ask yourself:
Are there parts of my application that I could reuse in other parts of my application? Then these could be taken out of your script and be put in a function or class.
Is there a scenario where you would like to exchange parts of your code to change the behaviour without having to rewrite major parts of your application? Then classes and interfaces are for you.
Another good argument for using OOP principles is the increased testability of your code. Using interfaces allows you to exchange the actual object for a mock or stub at test time.
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.
By doing some research, one of the disadvantages often reported about Zend Framework is the amount of work required to get off the ground. For me this could be addressed if ZF had strong model and backend interface generators like Symfony does. I have been looking for those and here is what I found:
Model generators
http://code.google.com/p/zend-db-model-generator/: looks like official one, based on user feedback, the documentation seems to be awful though.
http://code.google.com/p/zend-model-generator/: seems quite advanced. updated 3 months ago.
https://github.com/inxilpro/Galahad-FE/: not updated in 2 years, looks dead.
https://github.com/codeinchaos/zend-model-generator/blob/master/generate.php: single php file, could be interesting to use as basis and extend as needed.
Backend interfaces
As usual one can use database administration tools
http://www.phpmyadmin.net: quite complete with plenty of new features since 3.5. Hard to extend.
http://www.adminer.org/: single-file backend interface. Quite complete. The use of plugins seems to make extending functionality easy.
Backend interface generators
http://zfdatagrid.com/grid/default/site/crud which comes from what looks like a very active ZF related project: http://code.google.com/p/zfdatagrid/.
http://www.koala-framework.org/: I've recently come across this framework which allows you to create "desktop-like" applications around Zend, which one could use to create a backend interface.
Setting up the interface seems to be quite easy, for instance here is how you would display a form to edit contacts on the same page as you would edit members:
<?php
class MemberContacts extends Kwf_Model_Db
{
protected $_table = 'member_contacts';
protected $_referenceMap = array(
'Member' => array(
'column' => 'member_id',
'refModelClass' => 'Members',
)
);
}
?>
A demo of Koala frameworks is available. To be honest it looks quite impressive.
Q: Which model generators and backend interface (generators) do you use for Zend and why?
I do not use any kind of generator, prepared backoffice or so called scaffolding.
Why I don't use them in a general way ?
These tools introduce a strong dependencies on the way the generated UI is structured, you do not have anymore the power to design it the exact way you want.
They are quite hard to reuse unless you know them very well, they introduce a lot of magic, for example when I create a backoffice using Django I've to set five parameters and I've a backoffice running. Understanding how it works do really need a lot of knowledge on the inner mechanisms of the tool, so updating it can be a real pain.
To my mind there's a strong difference between providing almost complete backoffice application like Symfony, Rails and Django do, and what Zend Framework do: constraining to general framework and libraries.
There is a deliberate choice between something working out of the box and something flexible. I think they tend to aim different needs.
I tend to prefer the Zend Framework approach since I'm not satisfied (nor experienced I've to admit it) with what others offer as an "almost done" UI.
Why I won't ever use them in Zend Framework ?
If Zend Framework doesn't embend such tools, I won't plug what others have tried to build upon it since nothing can guaranty that there won't be any regression on it (and upgrading can be a really good thing since Zend always integrate more and more external services). The power of Zend Framework is its flexibility, by overlapping tools over it, you're going against the philosophy of the product.
It might meet your expectation on really small project, but for bigger one I do really suggest you to build your UI according to your own needs, the backoffice will only take only you one or two weeks more.
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 have the exact question that this guy has: http://groups.google.com/group/symfony2/browse_thread/thread/cd35132cc6972f29
I'll just copy-paste it here:
I was wondering what different ways of organizing bundles within a
project people are using.
I seem to end up with either one massive bundle for a project or a lot
of bundles which are closely related (dependant) to each other. eg;
I implemented my own user entity and login forms etc, but the users
are linked to an organization (with some functionality). Etc ... It's
mostly the entities that overlap a lot I guess ...
Do you guys split them up or dump them all in the same bundle?
Edit: I don't use bundles for app-specific code anymore.
Personally I prefer to have a bundle per a section of an application. For example:
UserBundle
BlogBundle
ForumBundle
JobBundle
StoreBundle
etc
This is okay if the app is a mishmash of several functionalities, none of which is big enough to require a separate application and/or a subdomain. But if I was developing a big webstore applicaton, my bundles would be more specific:
UserBundle
ProductBundle
CartBundle
SearchBundle
WishlistBundle
etc
So, I'd say, it depends on the focus of the project. What's just a section for one project could be the core functionality of another.
And I usually have CommonBundle, where all the common stuff goes, like global CSS, images, layouts, etc.
Also there are at least two options for the backend organization:
each bundle has its own backend section, or
there is one big backend bundle.
Personally I lean towards the first option and you can read about it in my previous answer, but there are people who prefer to have a separate bundle for the whole backend — probably using one of the admin bundles.
By the way, it's perfectly okay for bundles to be interconnected — you don't have to make them all independent of each other. For example, JMSDiExtraBundle depends on the metadata library and JMSAopBundle, which in turn depends on cg-library. If you'll try to keep bundles totally independent, you'll end up with big monolithic one-bundle lumps of code.
For every project I start off with one CoreBundle, where I put everything together. Then I just develop features in it and as time goes I reevaluate it - if I might use this feature somewhere else someday (or even release to open source), I move it to a new bundle.
"Size" of the feature worth separate bundle doesn't really matter - I've seen OS bundles as big as a 1 single js file :D
One thing for sure - stuffing everything in a single bundle is bad, it goes against the whole reason why this architecture was implemented in the first place!
My answer in the following topic can probably help you : Symfony 2 : Location of Entities
I'm not a Symfony2 master, but I think I have quite a good idea of the bundle design ; of course, there is no universal answer but you can follow some "best practices".
First of all, I don't think that big bundles are a good solution ; you doesn't split your project into applications anymore, like you did with Symfony1.4. You may ask "but what can I do with the frontend/backend logic ?" ; quite easy, use the controller !
Each bundle should refer to a module, a stone in your project's wall. You have to divide your application ; many bundles are not bad. Of course, don't do a bundle for each entities, that would be a waste of time. But imagine a blog application : you would have an User bundle, Articles bundle (which would manage posts, categories, ...), eventually a bundle for static pages, ...
It's not unlogical that your bundle are linked ; you are building a whole application, so in this case they are linked. But the keyword here is "generalization" ; your bundle should be able to be linked to others bundle, not only yours. You should be able to re-use it in others projects.
Good luck !
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.
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