How to Stop Wasting Time in PHP - php

As a programmer, I love developing algorithms. I love to take a problem and work out a clean, efficient, readable, elegant solution. I seem to find, however, that the majority of my time is spent validating and cleaning form data, and passing it along to prepare various SQL statements. Perhaps this is "just the way it is" but I suspect I may be doing it wrong.
What do you do to avoid the deathtrap of endlessly validating input and building database interactions? Do you use a third-party library? Write your own library? Or is that simply the way it is?

Most people abstract out a lot of the form validation and database transactions using some kind of framework. One example is the Zend framework Forms. I've seen people write their own libraries to add similar functionality.
For example, I've written my own simple library for smaller clients as well (just making each form element it's own class with a Basic "element" base class), a set of validation classes, and a Form class to wrap the elements. The form class calls the validate methods for each element and turns their data into an array that can be fed to a database class.
Your best bet is to figure out the needs for the websites and forms you are building. (Complex forms may be too difficult to abstract out). But simple forms could have their coding process stream lined without much difficulty.

If you're not using a framework (or can't), then you should definitely check out the php Filter methods: http://php.net/manual/en/book.filter.php
They're built in as of PHP 5.2
I've yet to see a good DB extraction outside of a framework, but the PDO abstraction layer is a good start ( http://php.net/manual/en/book.pdo.php )
P.S. I use Drupal too, when I can. The webform module in particular makes all this ridiculously easy.

I use Drupal for that, but you may prefer using some framework.

Related

Ajax loading for complex projects

My problem is actually not the ajax loading itself, more the capability to load it without javascript. I mean, I cope easily when I code my whole project just based on ajax-availability OR just without the use of ajax.
//EDIT: Although Arend already had a more or less valid answer, at the same time 'there is no direct answer to this question'. However, I'd like to see some other approaches of developers for scenarios like mine though! Even just a few links can help!
Basically I just get frustrated, coding everything twice on the same page to make sure that both users without and with Javascript enabled have the same experience. It's annoying and I was always wondering how others solve this problem.
When I update for example two divs with dependency on the same variables, it gets messy. Here's an example:
non-js-version
require 'classobject.class.php';
$another_var = 'something';
$class = new classobject($_POST['variable']); // just an example to show that this is dynamic - I'm aware of injection!
$function = $class->returnsth(); // returns 1
if(isset($_POST)) {
echo '<div id="one">Module 1 says:'; $require 'module_one.php'; echo '</div>';
echo '<br /><br />';
echo '<div id="two">Module 2 says:'; $require 'module_two.php'; echo '</div>';
}
Now in module_two.php and module_two.php I have code that executes differently depending on the return variable of $function.
Like:
if($function >= 1 && another_var != 'something') {
// do stuff
}
else {
// do other stuff
}
Now as this works easily with a reload, when I want to load the two modules on keyUp/enter/submit or whatever, I have basically a few problems:
I have to send the $_POST variables manually to the modules to use them
I have to re-execute the class & it's methods and make a link (require_once) to them in each of the module-files.
As $another_var is not existent in the modules, I'd have to send this variable to each modules, too (with post for example) and then before it can be used, I'd have to 'change' it like $another_var = $_POST['another_var'];
I find this mildly annoying and I wonder how you guys do that. I hope my way of coding is not too silly, but I can't think of another way. It's probably hard to relate to my very basic example, but to bring a whole project with the code would be too much. To sum it up, I'm looking for a better way to code and clean this mess up - there must be a way! I thought about sessions, but for compatability I don't want to rely on them either (if someone doesn't allow cookies).
In case you can't relate to what I'm trying to accomplish with that way of having my code assembled, I'll explain a scenario I'm facing quite a lot (not important if you already understand my misery):
Basically I have my index.php page where everything gets executed, with the html body and css styling and so on. This page expects some variables, that get set from the page that requires the index (like $another_var in my example).
Now other variables can get set too (from a form for example). Depending on that different classes and methods load new variables (arrays) that get used in while-loops in my modules to echo everything out.
Hope that's not too abstract. Think of a booking system where some variables are set from the page you are coming from (the event you want to book) and then a few more things get set by the user (a timespan, some preferences,...). In the end it's supposed to show results from the database all the way to the end-result - you can say the user narrows the results from step to step.
There is no direct answer to your question, but there is some food for thought.
Seperation of concerns
You can think about if you can perhaps seperate your buisness logic and layout logic. Often the use of a template engine can help greatly with that. I've had positive experiences with for example Twig or Smarty (was some time ago, not sure how they measure up right now). It requires you to write your code in a (less linear) way, but more logical.
A typical example of an OOP like seperation of concerns might be something like this:
$this->setParam('Myparam','myvalue');
if ($this->isAjax())
{
$this->setTemplate('ajax.php');
$this->setLayout(false);
} else {
$this->setTemplate('normal.php');
$this->setLayout('Mylayout');
}
return $this->render();
It is an imaginative situation, which can be found in many MVC like applications and frameworks. The main idea is that you should have the possibility to seperate your layout from your data. I would suggest looking at some of the modern frameworks for inspiration (like symfony, codeigniter, zend framework).
Glossary / Often applied concepts in a decoupled PHP application
Here is a quick list of concepts that can be used.
Example mvc in php: http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
Note: I don't really like the implementation. I much more prefer the existing frameworks. I do like the explanation in total of this tutorial. E.g. for me this link is for learning, not for implementing.
Silex
For a simple decoupled php micro-framework I would really recommend silex, by the makes of symfony2. It's easy to implement, and to learn, but contains mainy of the concepts described here; and uses all the php 5.3+ goodies such as namespacing and closures.
see: http://silex.sensiolabs.org/
Frontcontroller Pattern
Only have one, and one only point of entry for your code. I usually only have one, and one only point in your application. Usually a frontcontroller 'dispatches' the request to the rest of the application
http://en.wikipedia.org/wiki/Front_Controller_pattern
Routing
A routing system is often used in combination with the frontcontroller pattern. It basically describes which URL is connected to which module / controller. This allows you to change the way people access your app without changing the urls.
See: https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Controller
A controller is the place where buisness logic is applied. Getting the data from the database, checking privileges, setting the template, setting the layout, etc. (although this is also moved outside the controller if it becomes too big of a seperate concern).
Model
The model basically is the layer in which use manage your database. This can be a simple class where you move all your mysql_* functions, or it can be a full-featured ORM. The main philosphy is that all the logic related to fetching and placing information in the database is seperated.
One step up: ORM
An often used method in applications are Object Relational Models, these 'map' SQL records to PHP objects. Doctrine and Propel are two of these well worked out libraries. I heavily rely on these systems in my development. In this sense, the doctrine or propel part will represent the model layer.
Doctrine: http://www.doctrine-project.org/
Propel: http://www.propelorm.org/
Other ORMS: Good PHP ORM Library?
PHP ORMs: Doctrine vs. Propel
View:
The view usually consists of a templating engine. Some use plain PHP as a template, others, such as symfony create a seperate scope in which variables are placed. There are many discussions and opinions about what is best, one is right here on stackoverflow:
Why should I use templating system in PHP?
PHP vs template engine
Ones I like:
- Twig: http://twig.sensiolabs.org/
- sfTemplate: http://components.symfony-project.org/templating/
- Smarty: http://components.symfony-project.org/templating/
Decoupling mechanisms:
Event based systems
Using events in your can help to seperate the code. For example if you want to send an email after a record has been saved, events are a good solution to do that; in general the model should not have to know about email. Thus events are a way to connect them: you can let your -email-send-class listen to certain records in order for them to send the right email. (Perhaps you'd rather want your e-mails send from your controller, this is probably a matter of taste).
Dependency injection
When using OOP code in PHP many relied on having singleton classes running around (configuration, etc). From an OOP point of view, this can be considered bad, because it's hard to test it, and it's not considered very elegant to have dependencies running around like that. Dependency Injection is a pattern that came form Java and is now used in the newer frameworks to get around this. It might be a bit difficult to wrap your head around, but you will see it coming back in several new frameworks.
Dependency injection in php: Dependency Injection in PHP 5.3
Frameworks:
A lot of these methods are difficult, or a lot of work to implement yourself. Many will reside to a framework for this. You may or may not need a framework. You may, or may not want to you a framework, it's your choice. But it's still useful to learn how the frameworks do it, and not try to reinvent the wheel yourself.
The no-framework php frameworks: https://stackoverflow.com/questions/694929/whats-your-no-framework-php-framework
Good habits: https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way
Frameworks worth looking at (imho): CodeIgniter, Kahona, CakePHP, Symfony (1.4/2.0), Silex, Zend Franework, Yii. There are many many more, each with their dedicated fans and haters.
I wrote something like this with PHP. I already had abstracted the rendering of every page such that I define a $content variable and then require('layout.php'). The $content variable is just a big HTML string.
I wrote a PHP function to determine if request was AJAX or not.
The non-AJAX responses render the layout with $content in the middle, b/t header and footer layout content.
AJAX requests basically get this: json_encode(Array("content"=>$content)). And I use jQuery to get the HTML out of the JSON response and modify the DOM. Using json_encode() will handle escaping the string for javascript.
In the end, I effectively have AJAXified every page w/o over-engineering a complex solution.
Any browser that supports AJAX can also open a link in a new tab/window to simulate the non-AJAX request. (Or bookmark/share a link, too.)

relearning PHP, how has it changed?

I'm planning on creating a small web app using PHP. The last time I used PHP was sometime around 2002/2003 where the code tended to be a horrid mash of PHP/HTML and Javascript shoved in a single file. I think I might have even been using PHP3...
I now want to relearn and want to know what's changed and what helper libraries and tooklits exist that might save me from unknowingly reinventing things.
E.g is there a "standard" MySQL library, or do we still use the basic PHP functions (as a side question, do stored procedures work in MySQL yet?)? What do I need to know in order to make a "modern" website that doesn't rely on whole page HTML form posts to send data back to the server, etc.
Welcome back. PHP has gotten better!
If you can, start using 5.3 from the start; be aware though that many web hosts don't support it yet (if that is an issue). If confronted with PHP 4, run away screaming: It is no longer fit for production use.
The major development is finally proper OOP in PHP 5. Getting familiar with that is the only really mandatory thing in my eyes.
Several popular frameworks have evolved that do a lot of low-level work for you. The Zend Framework is a very high-quality code base to work with and my personal favourite because it's also usable as a component library that doesn't force its design principles upon you; there are others. (Here is a comparison site).
PDO is definitely the low-level database class de jour. It has parametrized queries preventing SQL injection and supports a number of databases.
The MVC design pattern is a very popular design pattern for building dynamic web sites and applications, and is embedded as a design philosophy into most PHP frameworks.
Class Autoloading is a great new PHP 5 feature.
A relatively little-noticed new development is the Standard PHP Library that brings clean, OOP solutions to everyday PHP problems. For example the DirectoryIterator that allows for easy recursive walking through directories; the ArrayObject provides an OOP interface to many (but not all) core array functions.
The DateTime class will replace the old UNIX timestamps over time. It provides improved functionality, and can work with dates beyond the 32 bit timestamp's 1970-2038 range.
This is some of the stuff under the hood. There are important client-side developments you want to be at least aware of; namely Ajax to fetch server-side data without reloading the page, and using a JavaScript Framework like jQuery to deal with the details. CSS you will already be familiar with.
Move to Zend framework when you start , first do some good research on OOP. Make sure you are understanding well terms as polymorphizm and inheritance. The last thing you must learn are php patterns like singletone pattern and factory pattern , abstract classes and interface implementation.
Here are solutions:
Use ORM to abstract from SQL >> E.g is there a "standard" MySQL library, or do we still use the basic PHP functions
Use MVC framework >> helper libraries and tooklits exist
Use Javascript for better user experience JS Frameworks >> make a "modern" website

Custom PHP Framework Feedback

I've been learning OOP programming for about a year and a half now and have developed a fairly standard framework to which I generally abide by. I'd love some feedback or input on how I might improve some functionality or if there are some things I'm overlooking.
VIEW MODE
1) Essentially everything starts at the Index.php page. The first thing I do is require my "packages.php" file that is basically a config file that imports all of the classes and function lists I'll be using.
2) I have no direct communication between my index.php file and my classes, what I've done is "pretty them up" with my viewfunctions.php file which is essentially just a conduit to the classes so that in my html I can write <?php get_title('page'); ?> instead of <?php echo $pageClass->get_title('page'); ?> Plus, I can run a couple small booleans and what not in the view function script that can better tailor the output of the class.
3) Any information brought in via the database is started from it's corresponding class that has direct communication with the database class, the only class that is allowed direct to communicate with the database (allowed in the sense that I run all of my queries with custom class code).
INPUT MODE
1) Any user input is sent to my userFunctions.php.
2) My security class is then instantiated where I send whatever user input that has been posted for verification and validation.
3) If the input passes my security check, I then pass it to my DB class for input into my Database.
php general model http://img139.imageshack.us/img139/3319/phpmodel.gif
FEEDBACK
I'm wondering if there are any glaringly obvious pitfalls to the general structure, or ways I can improve this.
Thank you in advance for your input. I know there is real no "right" answer for this, but I imagine a couple up votes would be in order for some strong advice regarding building frameworks.
-J
One thing I would recommend you do is to go ahead and separate your functions into classes. I understand the points you made about avoiding instantiations but consider this: any framework will, by necessity, begin to accumulate a large number of functions.
Instead of doing
<?php get_title('page'); ?>
you would be better served to create a Page class with all of its functions inside of said class which you call statically. Then, your code becomes
<?php Page::GetTitle('page'); ?>
a much more descriptive naming convention and will become critical later on when trying to avoid naming collisions (you only have to avoid name collisions on say, 50 classes, rather than two thousand functions).
I would study up on the Model-View-Controller design methodology (as ircmaxell hinted at in his post). A lot of very powerful and very well-written frameworks apply this principle, and not just PHP frameworks either. My suggestion - study Yii for how your application should be controlled - very slick and the creator makes excellent use of static variables to control class instantiation.
Good luck with your framework!
Well, the only issue that I can see (without seeing code), is that SQL will be everywhere. What I'd suggest is creating a "model" layer in front of the DB connection class. That way, all your sql is in one spot (break it off into multiple models, etc). It makes maintenance MUCH easier (if you want to add a column to a table, optimize a query, etc)...
Otherwise, it looks like a good start!
Nice presentation. I would definitely look under the hood at other popular frameworks for some insight.
At first glance, I would suggest to see if you can find a way to only load the classes you need per request. Loading them all for every request may become unfeasible if the class library grows large.
Are you using autoloaders? It seems that you will be using a lot of requires... maybe I am just misinterpreting. I think it is great that you are writing your own framework. I don't see it as "reinventing the wheel" either as you are writing it to accomplish the tasks you want to accomplish and can control the overall weight of your project as well as, since you are by most standards still moderately new to OOP, learning a ton I am sure from the experience. Creating your own frameworks, trying to improve other peoples code and learning how others do things and why is an amazing learning experience and in my opinion will drastically improve your programming skills and understanding.

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