views:

3334

answers:

14

Even with a ton of PHP frameworks out there to choose from, I know many people prefer a minimal, personal set of libraries. What is your method when it comes to 'rolling your own' framework for PHP applications, and how does it vary depending on the type/scope of a project?

What does your script look like for a typical page? What is your file structure? What 3rd party libraries/components do you commonly use, and how do you keep your libraries, functions, classes organized?

Do you address/implement:

  • DB abstraction
  • REST
  • OOP
  • MVC

and if so, how?

At what point do you consider using a more popular, existing framework (eg. Codeigniter) instead?

Things that got me thinking:
The no-framework PHP MVC framework
What PHP application design/design patterns do you use?
Whats A Good Standard Code Layout for a PHP Application?
Scalable and Flexible Directory Structure for Web Applications

+2  A: 

I found a Simple PHP Framework...and it looks like a fantastic "no framework" framework ;)

Abi Noda
This is not even MVC!
RobertPitt
+2  A: 

For any medium-size sites i tend to go with a good framework that fits the role - CI is usually a good choice.

For small pages, i have my own implementation of an ultra-lightweight (and fast) MVC "framework". It's not really a framework, as all it does is request routing/dispatching but it allows me to have a site structure very similar to, for example, CodeIgniter:

app/
 myMvcLib.php
 controllers/
 models/
 views/
public_html/
 index.php

As for DB abstraction (again, on very small sites) i feel using PDO (using OOP) provides me with enough functionality to get things done, and quickly enough.

jcinacio
If you wanted more DB abstraction, would you build it using PDO?
Abi Noda
Probably, yes. i don't see PDO having a major effect on speed over "regular" DB drivers and i feel the standard interface helps keeping the code clean.
jcinacio
+6  A: 

You might want to check some minimalistic PHP Frameworks:

I think they are simple, clean and fast enough.

Any of them will allow to use any model or object relation mapping (ORM) tool (like Propel, Doctrine, CoughPHP, etc...), althought Simple PHP Framework features a basic Active Record based model.

CMS
+14  A: 

Most of the time I use CodeIgniter, but there are times when I just need to make a quick change/addition to something which is already up and running.

In an ideal world, this is the no-framework framework I'd like to use one day:

  • app
    • controllers
    • models
    • views
    • config (db config, etc)
    • emails (templates for emails sent out by the system)
    • lib (common class files for pagination, db stuff, etc)
  • index.php (Front controller)
  • .htaccess

In the real world, with deadline constraints, this is how i actually end up doing thngs (however someday I'm going to build the framework I mentioned above):

  • app
    • script.php
    • another-script.php
    • yet-another-script.php
    • admin
      • login.php
      • users.php
      • something-else.php
    • inc
      • db-config.php
      • Db.php (Database class)
      • Auth.php (user auth. class)
      • functions.php (functions common throughout the system)
      • ........
Click Upvote
In the deadline world, we just have to do, no matter how! very very nice separation.
Sepehr Lajevardi
+1  A: 

I'm making my own framework to use.

I've set standards for the following,

standard datatree multidemensional array

standard way to process get/post data

then I build modules that work with each other and can be combined to make larger programs

e.g. a page program that handles the display of a page with several components.

that uses a html-text component, and image component and even a video component, and can use any other type of content I would want in the future.

the page system works in tandem with a navigation system, and they all work with a version control module.

Each time I build a site I consider how to make it out of reusable modules.

I do the same thing with my javascript functions so as I go I"m building my own framework over time.

I think that I can make decisions about my framework that make them more effective for my use than any prebuilt framework would, because when I build it for myself I can take alot of options off the table, things needed for projects that are outside my core market, that's what makes a custom framework more effective over a generalized one, it can be more specific.

Fire Crow
I think building your own will teach you a lot. I tried to do the same and found it very useful. In the end I got bored of reinventing the wheel though, so these days I use Code Igniter.
Jon Winstanley
Downvote me if you like, I believe in custom solution based programming, what has programming come to when programmers just reuse other peoples code.
Fire Crow
"what has programming come to when programmers just reuse other peoples code" I'd say it's coming to what any other normal, respectable engineering task already is.
Adriano Varoli Piazza
Thanks, that explains a lot.
Fire Crow
+1  A: 

Currently, I maintain two projects built without an external framework. One is my blog, written a long time ago in two days and improved from time to time since then. The code is short, simple, fast and works, but is a bit messy and more complex functionality is hard to add in an elegant way (in fact, it was written to be rewritten as soon as possible, but it works for 4 years now :)). The only external libraries are GeSHi for syntax highlighting and OPT template engine.

Another project is a CMS with a small MVC core. It uses OPT, dedicated form processing tool and PDO extended with caching features and small improvements that speed up the programming. It also will be rewritten some day.

Zyx
A: 

I just about never touch php without the use of smarty. This by itself enforces a bit of structure to the app (though not terribly much) and smarty can be put to a tremendous amount of work.

TokenMacGuy
Hmmm, interesting. I've read a lot of people saying that Smarty is unnecessary—an abstraction too many.
Abi Noda
with almost no other work, smarty gives a clean separation between logic and presentation. Since I don't really drink ORM kool-aid, my models mostly end up as sql. Thats as much as i need for a mid-size project.
TokenMacGuy
i will second smarty. I think that code separation is a must for clean code.
gnomixa
I Agree with Abi, Its a pointless abstraction, With smartty you take the route of: `Template -> Smarty -> PHP -> Compiled Output` with PHP alone: `Template -> PHP -> Compiled Output` your just adding Smarty to change syntax, does not separate view from logic, You should just encapsulate your template loading in a name-space or a class with tight scope
RobertPitt
+3  A: 

My take on this has evolved over 9 years into a set of libraries (not a framework) that I am in the process of publishing: http://github.com/sandeepshetty/bombay/

I'm old school and know that good design is possible in any paradigm. I prefer using multiple paradigms and hate being locked into any one (I'm looking at all you OO-for-OO-sake frameworks).

Not much of a MVC fan since it doesn't feel like the right approach to web programming. However, I do believe in separating code from presentation and my approach is heavily influenced by REST and what I like to call Resource Oriented Programming. For me, the web site IS the API.

A note on file structure: I prefer modularity and try to keep my resource handlers self-contained so that they can easily be reused in other projects by coping them. This means that you won't find top level folders like views, controllers or models. Instead, I have top level folders like libraries and handlers (which further contain sub-folders per handler with all the code and templates that it needs).

Sandeep Shetty
Absolutely agree, I do the same!
pestaa
+3  A: 

This is my own invention, please don't downmod me for that. I used it for the web UI on an embedded device for Cisco and it worked flawlessly. It's size at 60 lines was advantageous both from a disk and processor perspective on embedded Linux:

http://code.google.com/p/barebonesmvc-php/

George Jempty
+2  A: 

I made this one for my own personal use, it consists of only 4 functions:

  • DB()
  • Route()
  • Singleton()
  • View()

It's inspired by NiceDog and DiBi. I use it primarily for simple websites and APIs, and I find the DB() function quite useful because it's quite easy to implement (zero configuration) and supports all the following features:

  • SQLite 3
  • Arrays for SELECTs
  • Last Insert ID for INSERTs
  • # of Affected Rows for UPDATEs, DELETEs, ...
  • Prepared Statements and Escaping similar to DiBi

I haven't written any documentation for this but it should be pretty easy to understand if you study the code for a couple of minutes.

PS: I only use this "framework" for test cases and sometimes for low traffic stuff, a full featured framework should be used if you're doing something serious.

Alix Axel
+2  A: 

I like flourish

knorthfield
+4  A: 

Take a look at PHP Fat-Free Framework. You don't even need to use it as an MVC framework if you want, but surely you'd want to get into some good programming practice right from the start. It's got a gentle learning curve, compact syntax, fast and powerful template engine, forms processor, CAPTCHA image generator, built-in Javascript/CSS compressor, URL-based caching, easy-to-use SQL handler, and most of all, in a single 55KB file!

stillstanding
+2  A: 

I use Dingo Framework. Its only 63kb

http://www.dingoframework.com/

application
-config
--deployment
--development
-controller
-error
-helper
-language
-model
-orm
-view
system
-core
-driver
-library
index.php

If you read the documentation (http://www.dingoframework.com/docs) I am not sure what else you really need in a FW?

Adam Patterson
+3  A: 

I love building my own framework from scratch, The most perfect framework to me would be something like so:

File Structure

  • .htaccess
  • index.php
    • /system/
      • /applications/
        • /front_end/
        • /back_end/
      • /libaries/
      • /requirements/

My index.php file would take care of defining certain constants like so:

define('ROOT_DIR',str_replace("\\","/",dirname(__FILE__)));

define('SYSTEM_DIR', ROOT_DIR . "/system");

define("FRAMEWORK_VER","1.0.0",true);

require_once SYSTEM_DIR . "/startup.php";

Simple as that, But within startup.php I would load the following criteria's for my framework:

  • SPL Autoloader, to load general classes / interfaces etc.
  • Load error checking class and start capturing output, encase some hook pre-sends whitespace
  • Create a registry objects to store objects like so:
    • Registry::add('Config',new Configuration_Loader());
    • Registry::get('Config')->system->host;
  • Clean all user input such as $_GET,$_POST,$_COOKIE with htmlentites
  • Load the route class and generate a route,
    • All this is for is to check for controller/method/param1 or ?c=test&m=test etc.
  • Once the raoute is bein found, I will send the route of to the Loader, witch in turns loads the required classes or throws a 404* error page.

when it comes down to the controller, as I have a registry object with a global scope i usually just do the following!

abstract class Controller
{
    public function __get($object)
    {
        return Registry::get($object);
    }
}

and then do like so:

class Controller_test extends Controller
{
    public function test()
    {
        $this->View->title = "Hello World";

        $this->output->send($this->View->compile("test_page"));
    }
}

I tend to never create a template system as PHP itself is a great template system, I usually compose my view system with 2 objects!

First object is the View class witch just has getters and setters for the template data, and then ViewCompiler witch loads the template within the scope of its class like so

class View
{
   //...
   public function compile($template_name)
   {
       $Data = ViewCompiler($template_name);
   }
   //...
}

Then within ViewCompiler:

class ViewCompiler
{
   public function __construct($root,$data)
   {
       ob_start();
            require_once TEMPLATE_DIRECTORY . $root . '.php';
       $data = ob_get_contents();
       ob_end_clean();
   }

   public function location()
   {
       //use func_get_args(), to compile a new Route! and return with BASE_HREF!
   }
}

Then you have a set of functions and helpers all locked in one class for the template system.

RobertPitt
I like it. One comment - cleaning _GET, _POST, and _COOKIES globally with htmlentities might not be the best idea. In my opinion it is better to keep input pure until each component needs to deal with input and let it decide how to clean (template cleans with htmlentities, database layer escapes appropriately, etc.). That way you don't end up saving `<` to your database or have to remember to decode it before saving.
Renesis
Treating all data in its entities is the best way to do deal with things, IMO.. Then just use a ORM / DBAL to deal with injection, within the Input class you would pass GET/POST etc into a local variable, then add a method to access pure entites such as `$input->get('some_key',true); // True for untouched values`
RobertPitt