Why is Zend Framework so popular? - php

I'm not a troll and my goal isn't to start a flame war; neither do I mean to disrespect the authors of the Zend Framework: there is a lot of fine work in it. But... I have a job to get done and I'm having a hard time reconciling the popularity of ZF against the reality of building apps with it. I would really like to know from others why they use Zend Framework.
I am fairly new to the PHP world but I've done a lot of programming in many languages. After reading many tutorials and building a couple of apps in it, some core Zend Framework facilities feel like alpha code to me. For me the following fundamental weaknesses, among others, would seem too overwhelming to consider deploying apps with it - but over and over again ZF is suggested as one of the, if not the leading framework.
First let me say I find the much of ZF to be workable. Routing works pretty much as it should, the Layout facility is serviceable (though very different from templating systems such as JSP/ASP), as is the cache facility, etc. There seems to be a tendency in the community to stuff a lot of modeling (e.g. validation) and view logic (e.g. $this->headScript() - why should my controller have to care which js file my view requires?) into controllers but could be a matter of usage and not necessarily the framework's fault.
Now for a couple of really serious (IMO) weaknesses I've experienced in my short time with it. I shudder to imagine the other areas I will discover in the future if I continue to build with it.
1. Form Layout
Many people seem to be unhappy with the lack of control over form layout. How can you have a popular framework where constructing a simple form requires so much discussion?
Question 1 and question 2.
2. Authentication/Authorization
No one really seems to understand how to simply perform routine authentication/authorization. People [including yours truly] struggle with implementing simple access control. Further, the approach seems to lean on serialization for persistence, rather than traditional database storage of users and permissions.
A confusing example, a proposal to enhance the facility, a tutorial - part I,
and part II. This is too much work guys!
Are my perceived weaknesses not real or somehow not a problem? Why or why not? Why did you choose Zend Framework (or not)? Are there other areas that you've found to be so painful that you want to dump ZF for a different approach? Thanks for your opinions.

Because they are good at Marketing
Zend's founders Andi Gutmans and Zeev
Suraski are key contributors to PHP
And they have one of the most complete framework for php.
When you think about it; it's like saying:
"Our language isn't as performant as it could be, so we made a framework with caching that makes it faster"
Most of what Zend offer, can be done
without Zend.
But Zend's package is a very good
"All in one" distribution.
They offer certifications and trainings.

One of the main benefits of ZF is that you can take any one of it's components and easily tie them in with your own (or a third party) framework with minimal modification.

Forms: The decorator approach is complicated, but bulletproof and priceless for applications with many forms. You don't care if you have 10 or 25 items in your form, the style is always the same. Saves you a great deal of work when you know how to use it.
For users with simplier minds and goals there is always the viewScript decorator ;)
Auth/Acl: Never had any problems with these.
Zend_Auth::getInstance()->hasIdentity() //logged in
and
Zend_Auth::getInstance()->getIdentity()->role; //returns admin
For Acl:
$acl->isAllowed($who, $where, $what);
$acl->isAllowed('roleAdmin', 'resourcePosts', 'create'); //returns true
Can be easily modified to match MVC:
$acl->isAllowed('roleAdmin', $module.ucfirst($controller), $action); //returns true
$acl->isAllowed('roleAdmin', 'adminPosts', 'create'); //returns true

Color me UNIMPRESSED with ZendFramework. Using Zend Framework is like welding a set of training wheels to your code. Anything you can do in Zend Framework is something you can do in raw PHP. (Remember ZF itself was written in raw PHP.) And you can usually do it with the same number of lines of code - written in a consistent style with the rest of your application. And, by using native PHP code, you're not locked into a niche tool that only a minority of PHP developers use. And you don't have to worry about compatibility with changes in ZF versions.
In my applications, I do all the same things that the ZF tools do, mostly by using simple PHP functions that have been around for years:
validate form data
cleanse form input
handle files uploaded through forms
manipulate and compare dates
handle authentication
send emails
write to log files
read from configuration files
read external HTTP pages
exchange in JSON and SOAP formats
work with third-party APIs
I can't find much of anything in Zend Framework that is worth my time. And don't get me started on overbearing "scaffolding" frameworks like CodeCoffin, AppShackler, or Ruby in Chains.

ZF is a good starting point. I used zend_tool to generate a MVC skeleton of my middle-size application and used many other components (Zend_Cache, e-mail, translate, forms, session).
And I agree that form layout is complicated if you are trying to do it as Zend says - with decorators. There are ways to use just Zend_Form elements with validation and in your custom layout - without decorators.
I had a bad experience with Zend Cookies - I just could not set a cookie for my entire domain. Old good setcookie did the trick right.
About Acl - again, examples in Zend documentation and Zend_Acl do not work well sometimes. I used Controller plugin approach and my own "role based resource management" to control permissions.
I did not even try Zend Data Gateway - used Doctrine instead (I guess that is because I like nHibernate :) ) And connecting Doctrine was really easy.
I think ZF is good because you can use it as you like. I think it would be harder with some other frameworks.

Simplicity to build medium size applications.
Until ZF you had to build your own "framework" to do medium size applications. Now is much more simpler.
I don't think decoupling and simple elements that can be used independently is the key to success. Is a nice feature, but is not the regular use.
Support and community size are relevant in the balance with other frameworks.
In terms of speed they are NOT better then other frameworks.

Wel, we are developers because we are supposed to be able to write "some" of our own code, arn't we? Frameworks not supposed to be wizards, just an added assistance.

I did not choose Zend Framework because at the time when I was evaluating PHP frameworks it was not a complete and integrated enough solution for building web apps. I chose symfony and since then I have never had a need to switch to anything else.
I'm not sure if it's the same nowadays, but I always thought of ZF as a component library rather than a framework. A framework has a somewhat more strict rules of doing things and often has better integrated support tools to help people do them. A component library is more loose in this regard. When the framework rules correspond to the requirements of most applications in the framework's domain, I myself clearly prefer this solution. This has been the case with symfony for me. I do use certain ZF components as needed, but never base my projects on ZF itself.

I use ZF for a few reasons:
The host of nifty classes, lazy loading of classes, stand-alone usage of classes, and clean clear source. The first time I used it I needed to build an ACL system - a very big complex one. Zend_Acl helped tremendously.
I think ZF needs to work on it's docs and db classes. The db classes problems have a lot to do with PHP itself. So maybe it's some thing Zend wants to look into.
The OP is new to PHP. I agree PHP has it's flaws such as the arbitrary naming of functions, but generally it does make sense for HTTP and doesn't hide reality from you.

Form layout:
It's really easy. Decorators are a pain in the butt during your first contact with them, they're just black magic. Then you realise how useful they are and that you can do almost anything with them. When you finally hit a point where decorators are just not enough, you can just render separate form elements in your view or even write your own form HTML. Consider this example:
form
$text = new Zend_Form_Element_Text('text');
$text->addValidator('NotEmpty')->setRequired();
$submit = new Zend_Form_Element_Submit('submit');
view
<form>
<input type="text" id="text" name="text" />
<input type="submit" id="submit" name="submit" value="Send" />
</form>
controller:
$form = new Form_Whatever();
if ($this->_request->isPost()) {
if ($form->isValid($this->_request->getPost()) {
// code
}
}
There you go. You have a form, you wrote its HTML manually, but you still benefit from ZF's inbuilt validation. Why? Because you still create the form object in the controller and feed it the data sent via POST. You still get your filters, validators, anything you want. With any HTML you want. And you can also plug an external view to the form if you want to go extreme :).
Oh, by the way, did you know that your forms are reuseable? Yeah, you can write one form and use it in multiple places. No hassle. That's what I personally like about forms in ZF (and dislike in CodeIgniter - which is a great framework too, by the way).
Authentication:
Zend Framework: Login password hash, email validator?
Yes, it's only a small piece of code. You basically copy and paste it in your projects.
As for ACL, you just create your rules and then check them whenever you need them. A one liner. Can't be simpler.
Personally, I think ZF is popular because it simply saves your money. If you put me in front of a project, I can guarantee you that I'll finish it twice faster if you let me use ZF instead of another framework I know. And probably a fraction of the time I'd need to do everything in baseline PHP. So that's about it: saving time = saving money. Or earning you extra money - but either of the two rules, right?

There is no need to use Zend_Form or Decorators themselves. You can just use plain HTML Forms and then inside Controller=Actions use Zend_Filter_Input like this. So you have best of both Worlds.
public function indexAction()
{
$this->view->title = 'Search Results';
$filters = array('q' => array('StringTrim' , 'StripTags'));
$validators = array('q' => array('presence' => 'required'));
$input = new Zend_Filter_Input($filters, $validators, $_GET);
if ($input->isValid()) {
$this->view->messages = '';
$q = $input->getEscaped('q');
$this->view->q = $q;
// do search
try {
$index = News_Search_Lucene::open(
SearchIndexer::getIndexDirectory());
$results = $index->find($q);
} catch (Exception $e) {
$results = array();
}
$this->view->results = $results;
} else {
$this->view->messages = $input->getMessages();
}
}

I'm not sure if ZF is really the most popular PHP framework. I chose it after comparing it with other frameworks that do more stuff "magically" because they all seemed to hard to customize.
I think ZF is a good object oriented PHP MVC framework, but I don't agree with some ZF approaches. For example, I only use Zend_Form for filtering and validate data. All the HTML and presentation stuff are done at view scripts. The CSS is the responsible for the layout. If we need some changes most of the time changing only the CSS is enough. If I need to make the same form appear in many pages, I use it as a partial view script.
I don't like to have to write a Mapper for each Model and to create a Zend_Db_Table subclass for each database table. Instead I'm researching how to use other patterns for data access, or maybe Doctrine.
What I don't like about Zend_Acl is that stores the ACL information in the ACL file. I would like to store that information in the database.
The good thing about this framework is that is easy make things your way.

In addition to the previous answers, it is worth mentioning that in a recent pool at DZone titled Which PHP framework would you use today for a brand new application?, Zend Framework was selected to be the most preferable for new projects.

Related

Which PHP framework should I use for this project?

I have ready numerous posts here on SO about framework1 vs framework2 however it seems to be alot of personal opinions that are one sided. Based on the following can someone tell me which framework would be ideal for my needs?
Build a rich featured API where other sites and devices can use the API to use website features and access it's content.
RSS Feeds with both XML and JSON for jQuery interaction.
Ability to use layouts / templates that are customizable.
Use of plugins so that I do not need to duplicate code.
Database querying with relationships.
GREAT documentation.
Actively supported.
Doesn't REQUIRE command line access.
Easy to manage file uploads and move the files around so only certain users can download them.
Customizable access level so users can have different access levels depending on which project/section they are viewing.
Low overhead usage.
SEO URLS that do not require the '/view','/edit','/add' in the urls (depending on which action you want to do.)
Support for jQuery
There have been a few frameworks I have seen that support some of these but not all. I am currently using CakePHP for one project but do not think it would fit my needs as the database querying can get horrendous. I have heard a little bit about CodeIgnitor however it doesn't seem to easily use templating (maybe I just misunderstood what I read).
If you could tell me which framework you think would be ideal for these needs and why that would be very helpful!
I'll just spamvertize my little framework overview table here. The simple table answers a few of your technical points:
http://matrix.include-once.org/framework/simple
Use the detail/feature view to cherrypick your options.
RSS isn't a standard feature even with the big frameworks, use a PEAR library
templates: all frameworks use them
plugins: depends on your concept of plugins, most frameworks are extensible though
look for "ORM"
GREAT documentation: that would limit you to codeigniter or cakephp
Doesn't REQUIRE command line access: except symfony+cake, few do
file uploads: this isn't a standard feature, but I'd just mix and match a library
Customizable access level: practically all frameworks come with a permission system
Support for jQuery: this is surprising. Prototype seems to be very strong, only half the frameworks use jQuery by default
CakePHP database querying doesn't have to be horrendous. (Though, I remember my first few projects were definitely hard on the database)
With the right optimization, normalization/de-normalization of your data, and a few tweaks here and there (persistent models comes to mind), you can accomplish everything you've inquired about with CakePHP, and keep your database load to a minimum.
That said, if you truly want to move to something else, I'd go with Zend Framework.
Symfony is bloated, (and yes, fanboys, this is still true).
Codeigniter is super lightweight, but you're going to be doing a LOT more work to accomplish your listed requirements. I've spun up two codeigniter applications, both relatively simple, and both took twice the work / twice the amount of new code than if I had gone with say, CakePHP.
A lot of religious fanaticism floating around when you talk about frameworks. But take a look at the documentation of Fat-Free Framework. It just might catch your fancy and requirements.
Before I answer, let me qualify that I'm certified on Zend, a frequent user of CodeIgniter, and daily user (and hater) of Symfony.
Zend's setup, especially if you're doing a small-medium sized site can be ugly. Especially using the data mapper strategy, you're talking a thousand or more lines of codes just for the model setup. CodeIgniter is much better setup-wise, but still not insignificant.
Command-line free --essentially-- knocks out Zend. It's doable, but not fun (see thousand lines of code, above) Built-in user auth isn't nearly as good on CodeIgniter as Zend, perhaps that's a serious knock....definitely no templating there. Symfony is flat-out done because of the addition of /view /edit, etc.
Hate to break it to you, but it seems that many users of all these frameworks are not native English speakers. Forget about Symfony, seems entirely eastern-European based. I'd hate to be a new-to-php user of Zend Framework with all the competing tuts with their assumptions of some semi-complex concepts. There's a reason that Zend's training is expensive and full.... Again, CodeIgniter is not horrible, but still can be frustrating.
Simply because of our extensive use of Jquery and desire to avoid a ton of hack-around, my company has dumped the frameworks altogether. Now setup is purposeful, not for a framework...just build a DAL, assemble classes, build views, and done. Established functions are re-purposed as "plugins" that we actually know and understand. Most interaction is Jquery based Ajax (sometimes XAJAX) which really doesn't take advantage of the frameworks anyway--and fights tooth and nail with Symfony. For those who argue that frameworks force MVC, I have a VP of Development who does that just fine, thank you. Perhaps it's not the right answer for you, but we're glad we went this route. It's saved weeks worth of documentation-hunting.

PHP framework of intermediate complexity, in between CodeIgniter and Yii?

Something easy like CI (this means mandatory good, easy, up to date documentation). But also with some more features than CI.
Yii has lots of features, but it is also more complex (and it kind of forces you to have to use lots of it features). That means adding some functionality to your web-app takes three times as long because you have to figure out lots of new small functionalities of Yii.
It's kind of like the CI "gets out of your way" when it needs to, and Yii gets in your way, and if you don't do it its way, it breaks.
Features missing in CI that would be nice to have in this new "intermediate" PHP framework:
Code generation (crud).
Authentication.
Access control.
Layouts.
Widgets.
Easyer / automated pagination (like yii)
easy uri parameters
Where Yii causes me problems:
It's like for every small task there is some inbuilt functionality (this is good), but, YOU HAVE to use the inbuilt functionality, otherwise bad things happen. (CI gets out of your way, but does it too much, Yii helps a lot, but is butting in too much at times, and it forces you to sift through its documentation so that you discover these functions without which you are not able to accomplish a task that would take four time less, in CI, or in a non framework app).
Is there something in between ?
(ASP.NET MVC could be 'it', but I don't know the language, so the effort to learn it would be greater than learning Yii php framework really well, so I am looking for a PHP Framework)
I am a fan of CakePHP. I feel it has the specs you provided. If you want something more cutting edge you can take a look at Lithium
I have found some resources that kindof solve the problem, because they contain examples (Milan Babuškov's sugestion helped focus on "the solution").
Yii playground - examples
Yii cookbook - examples
Yii blog tutorial - more examples
PS. there is also google - I find solution (and examples) the fastest this way - ex: implement + pagination + yii
I've used both CI and Yii (on my own projects if that makes any difference). CI was my first introduction to MVC, and I found it easy going because it let me use any crappy structure and code. I wrote two full sites in CI (www.insolvencynews.com and www.thebigeat.com if you want to see complexity.)
I had a look at CakePHP but got NOWHERE.
Then I moved on to Yii and, like you, I found it pretty tough and rigid. But I then found that it was so powerful and extensible that I was so much more efficient. When I needed to add a few new features to the old CI sites, it was faster to rewrite the entire sites on Yii than to code up the extra features in CI.
I can't recommend a framework in the middle, but I can recommend sticking with Yii. When you say Yii gets in the way, can you give an example? Looking at DB stuff (in ascending order of dependence on Yii):
you can code using PHP's core MySQL functions.
$result = mysql_query($sql);
you can use Yii's DB abstraction layer.
Yii::app()->db->createCommand($sql)->queryAll();
You can use Yii's ActiveRecord:
Takeaway::model()->findAll();
you could try kohana (especially coming from ci)
You should check out the CI community, some of those extensions maybe have been written by someone else (I remember seeing Authentication and Components/Widgets somewhere)
Symfony is worth checking out. I personally don't like it much because they chose Prototype over jQuery for their ajax features, which is really annoying to use when you're used to jQuery.
Lithium might be good to check out too. However, it is php 5.3 only and you need to be really careful that this version of PHP is going to be supported on the server the site will be deployed on.
See this list for good comparisson:
http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP_2
From a personal point of view, I would go with symfony because of it's
rich features and
great integration with many other already bundeled components (Doctrine, Swift Mailer,..),
good (but at first complex) code generation that produces realy useable code to get you startet quickly,
powerfull use of templating (that will be the point you mention under "layouts)
many different, powerfull plug-ins, including Authentication & Access Control (it also has a plug-in to get jQuery support)
one of the best tutorials that I've seen with a framework
Downside is a
more complex structure,
IMO wired file structure,
a rather messy API documentaion compared to the tutorial
CodeIgniter is a nice framework if you don't want to create big apps but it lacks a great database integretaion and you already mentioned code generation.
im very good in Raw PHP, where the project at hand became too much to handle i decided to move to zend, with too too much complexity i finally moved to YII which really reduced the cost and overhead time for project development and most importantly for me is the simple integration of jquery, widget and advanced-OOP.
You could have a look at Qcodo / Qcubed.
They are both easy to pick up and offer code generation / ORM
Easy way to create forms in an mvc kind of way.
For what its worth, if you're looking for a PHP Framework that is like ASP.NET MVC then I think Prado is the closest thing you will find.

MVC as best practice for professional level programming?

Long time lurker, first time poster...
I'm now at the point where I'd almost call myself a professional grade PHP programmer and have a lot of code I re-use in various projects. Also, a lot of Open Source packages I've worked with use the MVC model and as a result I've done a lot of research recently into how it all works so I can better edit them as required.
At this point, I'm considering taking a bare-bones MVC framework (from a tutorial) and extending it as required for my forthcoming programming jobs.
My question is whether the MVC model with pretty much all application logic separated from the presentation layer is considered best practice over a well structured OOP website with coding on the page as necessary e.g setting function variables.
Or will I run into issues when I want coding flexibility e.g.
using something like PHPthumb for a gallery where I want different output
sizes on different pages and currently set parameters in the head
of the page
a contact form with x fields and a feedback form with y fields - will this require 2 differrent models rather than a generic form class again with some parameters set in the head of the page
some pages requiring ob_start() and ob_flush() but not others?
Please don't tell me not to build my own framework - I'd rather know how each little bit works than use a slab of code I know nothing about - I'm really interested in the opinion of people who have gone this route and build sites every day. What are the real pros and cons of this over plain (but well structured) OOP and bunch of pages to a site as opposed to 1 index.php page and separate files.
Cheers,
Niggles
I know you say you don't want this advice, but don't write your own. The first thing I've done at every single job I've ever worked at is picked up some existing code or framework, often commercial but highly modified, and begun maintaining it. You'll seldom get the option to write your own, and doing so is a bad idea. It's hard, expensive, and somebody else has already written a better MVC PHP framework than you're likely to write.
There are literally dozes of mature PHP frameworks, most of which have been around for over a decade. Choose one of them. It doesn't matter which one - they're all maintained by a dozen people at least as smart as you who've been writing MVC frameworks a lot longer, and have spent months or years refining their frameworks and listening to user input.
All that said, if you want to write your own on your own time, as a hobby, so you're not wasting your boss's money, then by all means. There's a huge variety of interpretations of MVC. Some frameworks view views as basically templates. I personally think you can throw as much raw PHP in there as you'd like, so long as it's purpose is display, and you do the usual smart things like distilling out shared code into functions. Some frameworks have virtually no business logic in the models (where it belongs IMO) but have very heavy controllers. The best thing you can do is try other frameworks and see how they work, and which you like best, and decide what you'd like to see changed. Then, set out to change it in your own.
You say you're almost ready to consider yourself a professional? The hardest lesson I had to learn was that professionals don't write their own low-level libraries. They don't reinvent the wheel on the company buck. They use off-the-shelf components and get the job done today, rather than a month from now. You don't want to use a slab of unfamiliar code? That's the biggest part of your life to come as a programmer - get used to it.
Writing your own framework is great for your own edification and for truly understanding the language.
Personally I find its as time consuming using a third party framework as it is to write your own. Yet I have total control of my own code, not something you can claim with any third party framework.
I also think many MVC frameworks are very resource intensive. For high volume sites you need to be prepared to throw hardware at them to get them to run nicely. For low volume sites (the majority) the rapid development of a third party MVC framework is a huge bonus.
So in my opinion if you have the time, roll your own and be proud of it. Just make sure you learn from others especially where security is concerned.
It all depends on what are you project requirements are and how you design your application objects. MVC do not force you to use an specific class or view design, It will only provide you with an architecture that will help you isolate the business logic from the presentation and the data layer making you application more scalable and easy to test.
In MVC you are not tied to one view per controller you can use as many views as you want per controller since every exposed method can call a view itself and control how it looks and behave based on the business logic you define. That said you can have 2 methods to return a full size image and a thumbnail without having to create two pages. You can set everything on the view from the controller, header meta-data, scripts, links, theme, content, etc...
In regard to the models, it again depends on your project requirements but definitely, in any case, if you have several pages with different purposes and they require to modify different data sources there should be a model for each one of them and what you can do after is to create a class that encapsulates the form functionality by calling the model for getting the fields to create form, get and save the data. This is just an idea you can do it in a lot of different ways, that is the beauty of OOP.
In the end it is not a matter of comparing a well structured OOP site against an OOP MVC site, It is more an analysis of the time and effort you spend working on building a site architecture that can succeed in isolating concerns at the same time it still readable and scalable while it meets your project requirements.
If you want to get more ideas about design patterns you can use google MVP design pattern and/or MVVM design pattern.
I have written my own framework. It does not take time to create the architecture and raw code. It's great if someone writes there own framework. But If documentation is not proper than definitely pain in asses. Completely depends upon yourself. I have written mine as well. It took almost 7 days to make framework QA ready :). but the main issue is to get satisfied by the piece of code you write in your framework. You would always like to improvise your framework and wanted it to be best ever. BLAH! BLAH! If you wish to write your own and you are confident enough for sustenance. GO for it.
Any MVC -- homegrown or not -- will allow you flexibility and re-usable code.
ob_start() / ob_* calls are no problem, they go in your model and called from your template, e.g.:
Hello <?php echo $this->getFormattedName(); ?>
where your model is
function getFormattedName() {
ob_start();
echo '' . $this->getName() . '';
$return = ob_end_clean();
return $return;
}
For your form scenario, you would probably want an abstract form class that defines how a field is made and its validation, then each specific form would extend your abstract.
You may want to consider using something like Zend Framework -- while it's an MVC library in its own right, you can pull in single components super easily (for example, you can pull in Zend_Form and Zend_Mail for your contact and feedback forms & validation and use your own models for everything else). This would also give you the extra benefit of having a fallback when/if the time comes when your homebrew MVC framework starts to outgrow its original design. Or, at the very least, speed up your development time so that you're not held up for days because you suddenly realize you need an e-mail model.

PHP Framework for form-intensive application

I'm looking for a simple-to-learn php framework for an application that is being migrated from Access to PHP. The application has lots of forms (sometimes 50+ fields per page), and lots of the fields are inter-dependent (ie, you change one field, it updates some other fields or options).
Is there any good php framework for this? I would prefer it really simple since:
The devs are not so experienced
The DB is being migrated from Access and was not designed with OOP in mind, it's basically a collection of tables divided by functionality, so I probably don't need any ORM (at least for now).
The most important thing is really the ease of form design and fields correlation (ex: two list boxes where the values of the second depends of the selected value of the first) - I know most ajax libs have some support for this but I would like it out of the box.
edit: As a clarification, the most important is not the ajax nifty stuff, although it is important. The important is a straightforward way to create db-based forms. The db is not designed with an ORM in mind, so I don't need fancy table associations on the ORM layer whith cascade deletes etc. If an ORM layer doesn't get in the way and simplifies the implementation so that's ok but i doubt this will ever be true.
I've just done a similar but much more simple application using codeIgniter, which has a pretty nice form helper
Examples of code:
form_hidden('userName', 'johndoe');
// Would produce: <input type="hidden" name="username" value="johndoe" />
form_input('username', #$_POST['userName'])
// Would produce an input populated with a variable from the post array
And you can do allsorts using arrays etc:
$js = 'id="shirts" onChange="some_function();"';
echo form_dropdown('shirts', $options, 'large', $js);
While I'll certainly add my support behind the excellent and simple to learn CodeIgniter I fear everyone so far is missing the elephant in the room regarding this question.
To be perfectly honest I don't think any framework is going to make assembling an application with 50+ forms per page simpler or easy for Developers without much experience. Especially with the added requirement of ajax ready support for dropdown dependencies.
Having said that, if you're looking for power and flexibilty I'd select Zend. If you're looking for straight simplicity I'd choose CodeIgniter.
Code Igniter has some very good documentation regarding forms and handles a lot of the complexities for you.
The form validation class is documented here: http://codeigniter.com/user_guide/libraries/form_validation.html
There is also a form helper class which makes creating forms very easy.
http://codeigniter.com/user_guide/helpers/form_helper.html
It is certainly easier than building a web app from scratch!
(source: codeigniter.com)
I'm a big symfony fan and it has pretty good support for forms with its form helpers. Check out the docs for forms:
http://www.symfony-project.org/book/1_2/10-Forms
Have a look at Zend Framework, in particular, Zend_Form.
It is enterprise ready, has excellent beginner to advanced tutorials as well as 'official' training courses, and it's free.
You also might want to check out CodeIgniter
the best is, without a doubt, Zebra_Form, a jQuery augmented PHP library for creating and validating HTML forms: provides both server-side and client-side validation (client-side validation is done using jQuery 1.5.2+) and has a lot of predefined rules that can be used out of the box; custom validation rules (including AJAX-based) can easily be added; has integrated cross-site scripting (XSS) prevention mechanism that automatically strips out potentially malicious code from the submitted data, and also features protection against cross-site request forgery (CSRF) attacks; it prevents automated SPAM posts, out of the box and without relying on CAPTCHAs by using honeypots; forms' layout can be generated either automatically or manually using templates; it's easy to learn, mature, and it is constantly improved;
Wow, this question is so outdated! Anyway, I also consider Symfony (SF) to be the best general purpose framework for PHP, however in SF 2.0+ forms are really complex (hence, complicated), and I don't consider Symfony to be a good option for form-intensive app, unless its requirements are quite specific. It's important to realize what you need: if it's the re-use of code (forms in this case), SF is really good, and their approach is very similar to the one took in the Java EE projects. But if you want results fast, I would look elsewhere, perhaps to Javascript frameworks.
If you want to work with JavaScript directly, look maybe at the jQuery Form Framework project.
Leaving general-purpose frameworks aside, for the UI-centric application I recommend ATK UI. It is relatively new (released in 2017) under MIT license. Here is why it's good choice for OP:
Designed for those who don't understand HTML / CSS.
Creating a form takes just few lines of PHP code.
Works with Database or without (up to you).
Handles wide range of types, even file uploads through extension.
Integrated with SemanticUI, fully responsive.
Installation: there is downloadable ZIP at www.agiletoolkit.org or through composer require atk4/ui.
Syntax:
<?php
$app = new \atk4\ui\App();
$app->initLayout('Centered');
$form = $app->add('Form');
$form->addField('name');
$form->addField('date', null, ['type'=>'date']);
$form->onSubmit(function($form){
return 'Hello, '.$name;
});
Nothing else is required, to need to install anything or copy assets, it just works. If you like, there are integrations with WP, Laravel and some other full-stack frameworks.

Fully Object Oriented framework in PHP

I want to create a 100% object oriented framework in PHP with no procedural programming at all, and where everything is an object. Much like Java except it will be done in PHP.
Any pointers at what features this thing should have, should it use any of the existing design patterns such as MVC? How creating objects for every table in the database would be possible, and how displaying of HTML templates etc would be done?
Please don't link to an existing framework because I want to do this on my own mainly as a learning excercise. You will be downvoted for linking to an existing framework as your answer and saying 'this does what you want'.
Some features I'd like to have are:
Very easy CRUD page generation
AJAX based pagination
Ajax based form validation if possible, or very easy form validation
Sortable tables
Ability to edit HTML templates using PHP
I've gone through many of problems on your list, so let me spec out how I handle it. I am also OOP addict and find object techniques extremely flexible and powerful yet elegant (if done correctly).
MVC - yes, hands down, MVC is a standard for web applications. It is well documented and understandable model. Furthermore, it does on application level what OOP does on class level, that is, it keeps things separated. Nice addition to MVC is Intercepting Filter pattern. It helps to attach filters for pre- and post-processing request and response. Common use is logging requests, benchmarking, access checking, caching, etc.
OOP representation of database tables/rows is also possible. I use DAO or ActiveRecord on daily basis. Another approach to ORM issues is Row Data Gateway and Table Data Gateway. Here's example implementation of TDG utilising ArrayAccess interface.
HTML templates also can be represented as objects. I use View objects in conjunction with Smarty template engine. I find this technique EXTREMELY flexible, quick, and easy to use. Object representing view should implement __set method so every property gets propagated into Smarty template. Additionally __toString method should be implemented to support views nesting. See example:
$s = new View();
$s->template = 'view/status-bar.tpl';
$s->username = "John Doe";
$page = new View();
$page->template = 'view/page.tpl';
$page->statusBar = $s;
echo $page;
Contents of view/status-bar.tpl:
<div id="status-bar"> Hello {$username} </div>
Contents of view/page.tpl:
<html>
<head>....</head>
<body>
<ul id="main-menu">.....</ul>
{$statusBar}
... rest of the page ...
</body>
</html>
This way you only need to echo $page and inner view (status bar) will be automatically transformed into HTML. Look at complete implementation here. By the way, using one of Intercepting Filters you can wrap the returned view with HTML footer and header, so you don't have to worry about returning complete page from your controller.
The question of whether to use Ajax or not should not be important at time of design. The framework should be flexible enough to support Ajax natively.
Form validation is definitely the thing that could be done in OO manner. Build complex validator object using Composite pattern. Composite validator should iterate through form fields and assigned simple validators and give you Yes/No answer. It also should return error messages so you can update the form (via Ajax or page reload).
Another handy element is automatic translation class for changing data in db to be suitable for user interface. For example, if you have INT(1) field in db representing boolean state and use checkbox in HTML that results in empty string or "on" in _POST or _GET array you cannot just assign one into another. Having translation service that alters the data to be suitable for View or for db is a clean way of sanitizing data. Also, complexity of translation class does not litter your controller code even during very complex transformations (like the one converting Wiki syntax into HTML).
Also i18n problems can be solved using object oriented techniques. I like using __ function (double underscore) to get localised messages. The function instead of performing a lookup and returning message gives me a Proxy object and pre-registers message for later lookup. Once Proxy object is pushed into View AND View is being converted into HTML, i18n backend does look up for all pre-registered messages. This way only one query is run that returns all requested messages.
Access controll issues can be addressed using Business Delegate pattern. I described it in my other Stackoverflow answer.
Finally, if you would like to play with existing code that is fully object oriented, take look at Tigermouse framework. There are some UML diagrams on the page that may help you understand how things work. Please feel free to take over further development of this project, as I have no more time to work on it.
Have a nice hacking!
Now at the risk of being downvoted, whilst at the same time being someone who is developing their own framework, I feel compelled to tell you to at least get some experience using existing frameworks. It doesn't have to be a vast amount of experience maybe do some beginner tutorials for each of the popular ones.
Considering the amount of time it takes to build a good framework, taking the time to look into what you like and loathe about existing solutions will pale in comparison. You don't even need to just look at php frameworks. Rails, Django etc are all popular for a reason.
Building a framework is rewarding, but you need a clear plan and understanding of the task at hand, which is where research comes in.
Some answers to your questions:
Yes, it should probably use MVC as the model view controller paradigm translates well into the world of web applications.
For creating models from records in tables in your database, look into ORM's and the Active Record pattern. Existing implementations to research that I know of include Doctrine, more can be found by searching on here.
For anything AJAX related I suggest using jQuery as a starting point as it makes AJAX very easy to get up and running.
Creating your own framework is a good way to gain an appreciation for some of the things that might be going on under the hood of other frameworks. If you're a perfectionist like me, it gives you a good excuse to agonize over every little detail (e.g. is should that object be called X or Y, should I use a static method or an instance method for this).
I wrote my own (almost completely OO framework a while ago), so here's my advice:
If you've worked with other frameworks before, consider what you liked/didn't like and make sure yours gives you exactly what you want.
I personally love the MVC pattern, I wouldn't dream of doing a project without it. If you like MVC, do it, if you don't don't bother.
If you want to do JavaScript/AJAX stuff, do use a JavaScript library. Coding all your own JavaScript from scratch teaches you a bit about the DOM and JavaScript in general, but ultimately its a waste of time, focus on making your app/framework better instead.
If you don't want to adopt another framework wholesale, take a look at whether there are other open source components you like and might want to use, such as Propel, Smarty, ADOdb, or PEAR components. Writing your own framework doesn't necessarily mean writing everything from scratch.
Use design patterns where they make sense (e.g. singletons for database access perhaps), but don't obsess over them. Ultimately do whatever you think produces the neatest code.
Lastly, I learned a lot by delving into a bit of Ruby on Rails philosophy, You may never use RoR (I didn't), but some of the concepts (especially Convention over Configuration) really resonated with me and really influenced my thinking.
Ultimately, unless your needs are special most people will be more productive if they adopt an existing framework. But reinventing the wheel does teach you more about wheels.
At the risk of sounding glib, this seems to me like any other software project, in this sense:
You need to define your requirements clearly, including motivation and priorities:
WHY do this? What are the key benefits you hope to realize? If the answer is "speed" you might do one thing, if it's "ease of coding" you might do another, if it's "learning experience" you might do a thid
what are the main problems you're trying to solve? And which are most important? Security? Easy UI generation? Scalability?
The answer to "what features it should have" really depends on answers to questions like those above.
Here are my suggestions:
Stop what you're doing.
It's already been done to death.
Click this Zend Framework or that CakePHP or maybe even this Recess Framework.
Now, my reasons:
... if you've worked with developers at all, you've worked with developers that love reinventing the wheel for no good reason. This is a very, very common failure pattern.
... they would go off and write hundreds and thousands of the crappiest languages you could possibly imagine ...
... "Oh, I'm gonna create my own framework, create my own everything," and it's all gonna be crappier than stuff you could just go out and get ...
from StackOverflow Podcast # 3.
So, save yourself some time, and work on something that solves a problem for people like a web app that lets people automatically update Twitter when their cat's litter box needs cleaning. The problem of "Object Oriented PHP Framework" is done. Whatever framework you slap together will never be as reliable or useful or feature rich as any of the freely available, fully supported frameworks available TODAY.
This doesn't mean you can't have a learning experience, but why do it in the dark, creating a framework that will grow into a useless blob of code, leaving you without anything to show for your time? Develop a web app, something for people to use and enjoy, I think you'll find the experience incredibly rewarding and EDUCATIONAL.
Like Jim OHalloran said, writing your own framework gives you a very good insight into how other frameworks do things.
That said, I've written a data-access layer before that almost completely abstracted away any SQL. Application code could request the relevant object and the abstraction layer did lots of magic to fetch the data only when it was needed, didn't needlessly re-fetch, saved only when it was changed, and supported putting some objects on different databases. It also supported replicated databases, and respected replication lag, and had an intelligent collection object. It was also highly extensible: the core was parameter driven and I could add a whole new object with about 15 lines of code - and got all the magic for free.
I've also written a CRUD layout engine which was used for a considerable percentage of a site. The core was parameter driven so it could run list and edit pages for anything, once you wrote a parameter list. It automatically did pagination, save-new-delete support etc etc, leveraging the object layer above. It wasn't object-oriented in and of itself, but it could have been made so.
In other words, a object-oriented framework in PHP is not only possible, it can be very efficient. This was all in PHP 4, BTW, and I bumped up against what was possible with PHP 4 objects a couple of times. :-)
I never got as far as a central dispatch that called objects, but I wasn't far away. I've worked with several frameworks that do that, though, and the file layout can get hairy quickly. For that reason, I would go for a dispatch system that is only as complex as it needs to be and no more. A simple action/view (which is almost MVC anyway) should get you more than far enough.
I initially started creating my own framework with similar ideals to your own. However, after a couple of months I realised I was re-creating work that had been done many times over. In the end I found an open source framework which was easily extendable and used it as a basis for my own development.
The features I implemented myself:
MVC Architecture
Authentication object
Database access class
URL rewriting config
Pagination class
Email class
Encryption
The features I looked at and thought, forget it! I'll build on top of someone elses:
Caching class
Form validation class
FTP class
Plugin-ability classes
Of course, writing a framework that outperforms the open source options is possible, but why would you bother?
It's true that some developers reinvent the wheel for no good reason. But because there are already good frameworks around doesn't mean that it's a waste of time doing one yourself. I started on one a while ago with no intention of using it for anything more than an exercise. I highly recommend doing it.
I've got the perfect link for you my friend: http://nettuts.com/tutorials/php/creating-a-php5-framework-part-1/. This is an awesome tutorial I have looked at, and its not too overwhelming. Plus look around the PHP section of that site I saw an article on CRUD. As for the AJAX look elsewhere, but you have to start somewhere, and this tutorial is awesome.
Note: this tutorial has 3 parts and I think it brings up MVC in the second instalment, but starts the first part using other methods.
The one, huge selling point I would look for in a new framework is that it would make writing testable code easy.
We typically work with Zend Framework, and it's mostly awesome, but trying to unit test/test drive ZF-based code is not far short of masochism.
If you could provide a framework that replaces the MVC parts of ZF with something that allows us to write testable code, whilst still allowing us to use the library parts of ZF, I will - quite literally - buy you a beer.
I'll buy you two beers if you ditch the AJAX. There's a huge gulf between an OO PHP framework and a JavaScript framework.
Please don't link to an existing framework
I will not, I started writing my own for learning purposes, and took a peek into some of the mainstream frameworks, and even with my limited knowledge see so many mistakes and bad ideas in them.
They're built by hardcore developers, not end users.
I'm in no way saying I could write better than the "big boys" but I (along with most of you I imagine) could point out why some things they do are bad, even if just because they're not end user/non-developer friendly...
I wonder how your framework is doing, some 6 years on?
Are you still working on it? Did you stop?
Should You Write Your Own Framework
This is probably a little late for you, but for anyone else, writing your own framework is a fantastic thing to do for learning purposes.
If, however, you are wanting to write one other than learning purposes, because you cannot work out the one you are using, or because it's too bloated, then do not!
Believe me, and don't be insulted, you would not be here contemplating it if you are a knowledgeable enough developer to do so successfully!
Last year I wanted to learn OOP/classes, and more advanced PHP.
And writing my own framework was the best thing I did (am actually still doing), as I have learned so much more than I anticipated.
Along the way I've learned (to name a few):
OOP/Classes many best practices which come with it - such as
Dependency Injection, SRP
Design patterns, which help you write code and structure your system
in such a way that it makes many things logical and easy. For an
example see Wiki - SOLID
Namespaces
PHP Error Handling and all of the functionality which that provides
A more robust (and better) understanding of MVC, and how to apply it
appropriately (as there is no clear cut way to use it, just guides
and best practices).
Autoloading (of classes for OOP)
Better code writing style and more structured layout, and better
commenting skills
Naming conventions (it's fun making your own, even if based on
common practices).
And many other basic PHP things which you invariably come across accidentally from reading something.
All of this not only vastly improved my grasp of PHP and things which come with it, to a more advanced level, but also some of the commercially/widely used methods and principles.
And this all boosted my confidence in using PHP in general, which in turns makes it easier to learn.
Why Write a Framework To Learn All of This
When you start out, you learn the basics - A (variables), then B (how to write a basic function), etc.
But it doesn't take long when you're trying to learn more advanced things, that to learn and use D and E, you also have to learn and understand F, G, H, and J, and to know those you have to know K, L, and M, and to know parts of L and M you first need to understand N and O...
It becomes a minefield as trying to learn one thing brings the need to first learn a few other things, and those other things often bring a need to understand various other things.
And you end up a mile away from where you started, your mind tingling and shooting sparks from it, and about 20 tabs open all with various advanced PHP things, none of which you are 100% comfortable with.
But over time, with practice and most certainly dedication, it will all fit into place, and you'll look back at code, even a collection of files/classes, and think "Did I write that.."?
Writing a framework helped greatly with this "minefield" because:
I had specific tasks to do, which brought about the need to learn and
implement other things, but specific things. This allowed me to focus
on less things at once, and even when something branches off to
various other things, you can reel it back in to where you started
because you are working on something specific. You can do this with
any learning, but if you do not have some goal, or specific task you
are focusing on, you can easily get distracted and lost in the ether
of things to learn.
I had something practical to work with. Often reading tutorials about
an animal class, and how cat and dog classes extend animal etc,
can be confusing. When you have a real life task in your own
framework, such as how do I manage XYZ, then you can learn how
classes work easier because you have trial and error and a solid
requirement which you understand, because you created the
requirement! Not just theory-like reading which means nothing
usually.
I could put it down when my mind was blown, although as it was my
framework (my Frankenstein's monster in the beginning :P) I wanted to
press on, because it was interesting, and a personal goal to learn
and sort the next stage, to resolve an issue I was stuck with, etc.
You can do it how you want. It might not be best practice, but as long as you are trying to learn best practice, over time you will improve, and likely easier than just reading tutorials, because you are in control of what and how you do something.
Wait, I Shouldn't Re-invent the Wheel Though
Well, firstly, you cannot reinvent the wheel, it is impossible, as you will just make a wheel.
When people say "Don't reinvent the wheel", they of course mean "there are already frameworks out there", and to be fair, they are written by skilled developers.
That's not to say the frameworks don't have problems or issues, but in general they are pretty solid, secure and well written.
But the statement is nonsensical in relation to writing your own framework!
Writing your own framework for learning purposes is really useful.
Even if you plan to use it commercially, or for your own website, you haven't just "re-invented the wheel", you've made something else.
Your framework won't be like the others, it won't have many features and functionality, which might be a major advantage to you!
As long as you understand about best security practices etc, because you can think you are writing a great system, which is super fast and without all the bloat other frameworks have, but in fact you have holes in places which someone could crawl into...
But a project for learning which you don't use on the internet is ideal - or use it, eventually, when you are advanced enough to know it's secure!
With all that said, you should write your own framework IF:
You are not needing it any time soon! It takes a lot of time as
there are so many aspects to consider, learn, and trial and error
leads to refactoring (a lot at first!)
You are willing to read, code, test, change, read, code, and read
some more. There is a lot of good advice on the internet for advanced
PHP, most of it mind blowing at first, like reading all the design
patterns. But they eventually make sense, and end up helping you
resolve problems you face, and how to do things within your
framework.
Willing to put the time in, and keep trying to improve, and head
towards best practice, especially with security. Speed issues shouldn't be an issue with a small framework, and besides, if you have a fairly decent system, you can usually refactor and make speed improvements. usually if you have significant speed issues it means you've chosen intensive operations, which can usually be addressed by doing it a different way.
.
Without previous experience, or an advanced knowledge of PHP, you will likely spend some time writing a framework, further reading and knowledge will show you that your approach is skewed, and so you might delete everything and start again.
Don't be disheartened by this.
I did exactly that, as I learned so much advanced patterns and ways of doing things along the way in the first month, I ended up where refactoring was no good, and a blank canvas with a whole new approach was the only option.
However, this was quite pleasing, as I saw a much better structure take form, and I could see not only a better framework foundation start to take place, but realised it was because I had a better understanding of advanced PHP.
Just do it! Just make sure you have a plan of what you want it to do before you even write some code.
Seriously, write down on paper how you are going to load error checking, are you going to have auto loading, or include files when needed? Are you going to have a centralised loading mechanism, which instantiates classes when you need them, or some other method?
Whatever you do, and whatever stage you are at, if you are heading into new territory, plan it first. You'll be glad of it when you hit a brick wall, can go back to your plans, and realise a slight deviation to your plans will resolve it.
Otherwise you just end up with a mess and no plan or way to re-deign it to resolve the current problem or requirement you face.
You are looking to build exactly same thing I've worked on for a few years and the result is Agile Toolkit.
Very easy CRUD page generation
$page->add('CRUD')->setModel('User');
AJAX based pagination
All pagination and many other things are implemented through a native support for AJAX and Object Reloading. Below code shows a themed button with random label. Button is reloaded if clicked showing new number.
$b=$page->add('Button')->setLabel(rand(1,50));
$b->js('click')->reload();
Ajax based form validation if possible, or very easy form validation
All form validations is AJAX based. Response from server is a JavaScript chain which instructs browser to either highlight and display error message or to redirect to a next page or perform any other javascript action.
Sortable tables
Table sorting and pagination has a very intuitive and simple implementation when you can really on object reloading.
Ability to edit HTML templates using PHP
This seems out of place and a wrong thing to do. Templates are better of in the VCS.

Categories