PHP Classes

How to Use a Simple PHP MVC Framework to Develop PHP Web Applications Using the Package PHP Light MVC: MVC framework to implement PHP Web applications

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2026-02-04 (18 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
phplightmvc 1.0BSD License5PHP 5, Libraries, Design Patterns
Description 

Author

This package provides a MVC framework to implement PHP Web applications.

It provides a router class that allows to map request URL patterns to action controllers that will handle the requests that match the URL patterns.

The package also provides base model classes that implement the ActiveRecord design pattern to store and retrieve model objects in tables of SQL databases.

It also supports processing view PHP scripts that work as templates to generate the output of the HTML Web pages or email messages.

Picture of Alvaro Talavera
Name: Alvaro Talavera <contact>
Classes: 1 package by
Country: Paraguay Paraguay
Age: ???
All time rank: Not yet ranked
Week rank: Not yet ranked

Instructions

Please read this document to learn how to create a PHP Web application using this MVC framework.

Example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title><?=SITE_NAME?></title>
   
    <style type="text/css" media="screen">
        .flash { padding: 10px; }
        .notice { background: #8FFF9F; color: green; }
        .error { background: #FFB0C6; color: red; }
    </style>
   
</head>

<body>
   
    <?Template::load('example.php');?>

    <?Flash::show()?>

    <h1>Example</h1>
   
    <h3>Asigned from controller:</h3>
    <p><?=$this->a_variable_name; ?></p>
    <p><?=$this->something_happen; ?></p>
   
    <h3>Params:</h3>
    <p><? String::pr($this->params); ?>

    <h3>Links Examples: (TODO: Improve this with helpers)</h3>
    <dl>
        <dt>With MOD_REWRITE</dt>
        <dd><a href="<?=WWW_PATH?>/example/messages">/example/messages</a></dd>
       
        <dd><a href="<?=WWW_PATH?>/example/index">/example/index</a></dd>
        <dd><a href="<?=WWW_PATH?>/example/show">/example/show</a></dd>
        <dd><a href="<?=WWW_PATH?>/example/show/1">/example/show/1</a></dd>
        <dd><a href="<?=WWW_PATH?>/example/show/1?other=2">/example/show/1?other=2</a></dd>
        <dd><a href="<?=WWW_PATH?>/mostrar/1">/mostrar/1</a></dd>
       
        <dd><a href="<?=WWW_PATH?>/example/show/1&other=10">/example/show/1&other=10</a></dd>
        <dd><a href="<?=WWW_PATH?>/mostrar/1&other=10">/mostrar/1&other=10</a></dd>
        <dd><a href="<?=WWW_PATH?>/mostrar/1/otra/10">/mostrar/1/otra/10</a></dd>
        <dd><a href="<?=WWW_PATH?>/mostrar_otro/1/10/cualquier-texto-extra-ignorado">/mostrar/1/otra2/10/cualquier-texto-extra-ignorado</a></dd>
    </dl>
   
    <dl>
        <dt>Without MOD_REWRITE</dt>
        <dd><a href="<?=WWW_PATH?>?url=/example/messages">/example/messages</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/example/index">/example/index</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/example/show">/example/show</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/example/show/1">/example/show/1</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/example/show/1&other=2">/example/show/1?other=2</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/mostrar/1">/mostrar/1</a></dd>
       
        <dd><a href="<?=WWW_PATH?>?url=/example/show/1&other=10">/example/show/1&other=10</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/mostrar/1&other=10">/mostrar/1&other=10</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/mostrar/1/otra/10">/mostrar/1/otra/10</a></dd>
        <dd><a href="<?=WWW_PATH?>?url=/mostrar_otro/1/10/cualquier-texto-extra-ignorado">/mostrar/1/otra2/10/cualquier-texto-extra-ignorado</a></dd>
       
    </dl>

</body>
</html>


Details

phpLightMVC

A lightweight, MVC-based PHP framework inspired by Ruby on Rails. phpLightMVC provides a simple yet powerful structure for building web applications with minimal configuration.

Features

  • MVC Architecture: Clean separation of concerns with Models, Views, and Controllers
  • Flexible Routing: Powerful URL routing system with support for custom routes, parameters, and optional segments
  • ActiveRecord ORM: Built-in PHP ActiveRecord implementation supporting MySQL, PostgreSQL, SQLite, and Oracle
  • Helper Classes: Rich set of utility classes for common tasks (String, Session, Cookie, Flash, Template, Upload, Crypto, etc.)
  • View Rendering: Automatic view rendering with support for custom templates and layouts
  • Before Filters: Controller callbacks for authentication and authorization
  • Flash Messages: Built-in flash message system for user notifications
  • Email Support: SMTP email sending with HTML template support
  • URL Rewriting: Works with or without mod_rewrite

Requirements

  • PHP 5.3 or higher
  • Apache with mod_rewrite (optional, but recommended)
  • MySQL, PostgreSQL, SQLite, or Oracle database

Installation

  1. Clone or download this repository to your web server directory
  2. Configure your web server to point to the `public` directory as the document root
  3. Copy the example environment file:
    cp .env.example .env
    
  4. Edit `.env` to configure your settings: - Database credentials - Site domain and paths - Email SMTP settings - Security vault key

Project Structure

phpLightMVC/
??? app/                    # Application code
?   ??? controllers/        # Controller classes
?   ?   ??? application_controller.php  # Base controller
?   ?   ??? example_controller.php     # Example controller
?   ??? models/            # Model classes (ActiveRecord)
?   ?   ??? Example.php
?   ??? views/             # View templates
?   ?   ??? example/       # Views for example controller
?   ?   ??? mails/         # Email templates
?   ?   ??? templates/     # Shared templates/layouts
?   ??? helpers/           # Helper classes
??? core/                  # Framework core
?   ??? boot.php           # Bootstrap file
?   ??? config.php         # Configuration
?   ??? routes.php         # Route definitions
?   ??? libs/              # Framework libraries
?       ??? framework/     # MVC framework classes
?       ??? classes/       # Utility classes
?       ??? active_record/ # ORM implementation
??? public/                # Public web root
    ??? index.php          # Entry point
    ??? .htaccess          # URL rewriting rules

Configuration

Configuration is managed via environment variables in the .env file.

APP_ENV=development
APP_DEBUG=true
APP_URL=http://localhost/path/to/public

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

SMTP_HOST=smtp.host.com
SMTP_PORT=25

SECURITY_VAULT=__your_secret_key_here__

Routing

Routes are defined in core/routes.php. The framework supports flexible URL patterns:

// Simple route
$map->connect("/", array('controller' => 'example', 'action' => 'index'));

// Route with parameter
$map->connect("/example/show/:id", array('controller' => 'example', 'action' => 'show'));

// Route with multiple parameters
$map->connect("/mostrar/:id/otra/:other", array('controller' => 'example', 'action' => 'show'));

// Route with wildcard
$map->connect("/mostrar_otro/:id/:other/*", array('controller' => 'example', 'action' => 'show'));

// Custom route
$map->connect("/login", array('controller' => 'example', 'action' => 'login'));

// Default catch-all route (must be last)
$map->connect(":controller/:action/*");

Route Parameters

  • `:variable` - Captures a URL segment as a parameter
  • `*array` - Captures multiple segments as an array
  • Parameters are available in controllers via `$this->params['get']['variable']`

Controllers

Controllers extend ApplicationController (which extends ActionController). They handle requests and prepare data for views.

Creating a Controller

Create a new file in app/controllers/ named your_name_controller.php:

<?php
class YourNameController extends ApplicationController {
    
    // Before filter - runs before every action
    protected function before_filter() {
        parent::before_filter();
        // Your code here
    }
    
    // Action method
    function index() {
        $this->variable_name = "Hello World";
        // Variables assigned to $this are available in views
    }
    
    // Action with parameters
    function show() {
        $id = $this->params['get']['id'];
        $this->item = Example::find($id);
    }
    
    // Redirect
    function create() {
        // ... save data ...
        $this->redirect(WWW_PATH . '/example/index');
    }
    
    // Custom render (no view)
    function api() {
        $this->render(json_encode($data), 'application/json');
    }
    
    // Disable view rendering
    function ajax() {
        $this->render(false);
        echo json_encode($data);
    }
}
?>

Controller Methods

  • `$this->params` - Access route and query parameters
  • `$this->render($content, $content_type)` - Custom rendering
  • `$this->redirect($url)` - Redirect to another URL
  • `$this->notice($message)` - Set flash notice message
  • `$this->error($message)` - Set flash error message
  • `$this->ajax($status, $data)` - Return JSON response

Models

Models use PHP ActiveRecord. They extend ActiveRecord\Model and provide an ORM interface to your database.

Creating a Model

Create a new file in app/models/ named YourModel.php:

<?php
class YourModel extends ActiveRecord\Model {
    
    static $table_name = 'your_table_name';
    
    // Define relationships
    static $has_many = array(
        array('comments')
    );
    
    static $belongs_to = array(
        array('user')
    );
    
    // Validations
    static $validates_presence_of = array(
        array('name'),
        array('email')
    );
}
?>

ActiveRecord Usage

// Find records
$user = User::find(1);
$users = User::all();
$user = User::find_by_email('user@example.com');

// Create
$user = new User();
$user->name = 'John';
$user->email = 'john@example.com';
$user->save();

// Update
$user = User::find(1);
$user->name = 'Jane';
$user->save();

// Delete
$user = User::find(1);
$user->delete();

// Query
$users = User::find('all', array('conditions' => array('active = ?', 1)));

For more ActiveRecord features, see the PHP ActiveRecord documentation.

Views

Views are PHP files located in app/views/{controller}/{action}.php. Variables assigned in controllers are available via $this->variable_name.

Example View

<!DOCTYPE html>
<html>
<head>
    <title><?= SITE_NAME ?></title>
</head>
<body>
    <h1><?= $this->variable_name ?></h1>
    
    <?php if (isset($this->items)): ?>
        <?php foreach ($this->items as $item): ?>
            <p><?= $item->name ?></p>
        <?php endforeach; ?>
    <?php endif; ?>
    
    <?php Flash::show() ?>
</body>
</html>

Templates

Load shared templates:

<?php Template::load('template_name.php'); ?>

Flash Messages

Display flash messages in views:

<?php Flash::show() ?>

Helper Classes

The framework includes several utility classes:

String

String::camelize('hello_world');      // 'HelloWorld'
String::underscore('HelloWorld');     // 'hello_world'
String::humanize('hello_world');      // 'Hello World'
String::sub('Long text', 10);         // 'Long text...'
String::url('Hello World');           // 'hello-world'
String::pr($array);                   // Pretty print array

Session

Session::set('key', 'value');
$value = Session::get('key');
Session::delete('key');
Session::clear();

Cookie

Cookie::set('key', 'value', 3600);
$value = Cookie::get('key');
Cookie::delete('key');

Flash

Flash::notice('Success message');
Flash::error('Error message');
Flash::show(); // Display in view

Template

$tmpl = Template::mail('email_template.php');
$tmpl->replace(array('name' => 'John'));
$html = $tmpl->render();

Sendmail

Sendmail::send(array(
    'to' => 'user@example.com',
    'subject' => 'Hello',
    'body' => $html_body
));

Upload

$upload = new Upload();
$upload->handle('file_field_name');
if ($upload->is_valid()) {
    $upload->save('/path/to/destination');
}

Crypto

$hash = Crypto::md5('password'); // Returns secure hash (bcrypt/argon2) $verify = Crypto::verify('password', $hash); // Returns true/false $token = Crypto::random_str(32); // Returns secure random string

URL Rewriting

With mod_rewrite (Recommended)

The .htaccess file in public/ handles URL rewriting. URLs work like: - /example/index - /example/show/1

Without mod_rewrite

If mod_rewrite is not available, use query parameters: - /?url=/example/index - /?url=/example/show/1

Examples

See app/controllers/example_controller.php and app/views/example/ for complete examples of: - Basic controller actions - Before filters - Redirects - Custom rendering - AJAX responses - Flash messages - View rendering

Author

Alvaro Talavera (alvarotala@gmail.com)

License

This framework is provided as-is for educational and development purposes.

Notes

  • The framework uses PHP short tags (`<?`). Ensure your PHP configuration has `short_open_tag = On` or convert to full tags (`<?php`)
  • Error reporting is configured in `core/config.php` - adjust for production
  • The ActiveRecord library is based on the PHP ActiveRecord project
  • Router implementation includes code inspired by the Akelos Framework

  Files folder image Files (56)  
File Role Description
Files folder imageapp (4 directories)
Files folder imagecore (3 files, 1 directory)
Files folder imagepublic (5 files)
Accessible without login Plain text file .env.example Data Auxiliary data
Accessible without login Plain text file README Doc. Read me

  Files folder image Files (56)  /  app  
File Role Description
Files folder imagecontrollers (2 files)
Files folder imagehelpers (1 file)
Files folder imagemodels (1 file)
Files folder imageviews (3 directories)

  Files folder image Files (56)  /  app  /  controllers  
File Role Description
  Plain text file application_controller.php Class Class source
  Plain text file example_controller.php Class Class source

  Files folder image Files (56)  /  app  /  helpers  
File Role Description
  Plain text file NameOfClass.php Class Class source

  Files folder image Files (56)  /  app  /  models  
File Role Description
  Plain text file Example.php Class Class source

  Files folder image Files (56)  /  app  /  views  
File Role Description
Files folder imageexample (2 files)
Files folder imagemails (1 file)
Files folder imagetemplates (1 file)

  Files folder image Files (56)  /  app  /  views  /  example  
File Role Description
  Accessible without login Plain text file index.php Example Example script
  Accessible without login Plain text file show.php Example Example script

  Files folder image Files (56)  /  app  /  views  /  mails  
File Role Description
  Accessible without login Plain text file example.php Aux. Configuration script

  Files folder image Files (56)  /  app  /  views  /  templates  
File Role Description
  Accessible without login Plain text file example.php Aux. Configuration script

  Files folder image Files (56)  /  core  
File Role Description
Files folder imagelibs (1 file, 3 directories)
  Accessible without login Plain text file boot.php Conf. Configuration script
  Accessible without login Plain text file config.php Conf. Configuration script
  Accessible without login Plain text file routes.php Conf. Configuration script

  Files folder image Files (56)  /  core  /  libs  
File Role Description
Files folder imageclasses (10 files, 1 directory)
Files folder imageextras (1 file)
Files folder imageframework (4 files)
  Plain text file class.base.php Class Class source

  Files folder image Files (56)  /  core  /  libs  /  classes  
File Role Description
Files folder imageactive_record (1 file, 1 directory)
  Plain text file class.cookie.php Class Class source
  Plain text file class.crypto.php Class Class source
  Plain text file class.env.php Class Class source
  Plain text file class.flash.php Class Class source
  Plain text file class.folder.php Class Class source
  Plain text file class.sendmail.php Class Class source
  Plain text file class.session.php Class Class source
  Plain text file class.string.php Class Class source
  Plain text file class.template.php Class Class source
  Plain text file class.upload.php Class Class source

  Files folder image Files (56)  /  core  /  libs  /  classes  /  active_record  
File Role Description
Files folder imagelib (17 files, 1 directory)
  Accessible without login Plain text file ActiveRecord.php Conf. ActiveRecord classes auto-loader

  Files folder image Files (56)  /  core  /  libs  /  classes  /  active_record  /  lib  
File Role Description
Files folder imageadapters (4 files)
  Plain text file CallBack.php Class Class source
  Plain text file Column.php Class Class source
  Plain text file Config.php Class Class source
  Plain text file Connection.php Class Class source
  Plain text file ConnectionManager.php Class Class source
  Plain text file Exceptions.php Class Class source
  Plain text file Expressions.php Class Class source
  Plain text file Inflector.php Class Class source
  Plain text file Model.php Class Class source
  Plain text file Reflections.php Class Class source
  Plain text file Relationship.php Class Class source
  Plain text file Serialization.php Class Class source
  Plain text file Singleton.php Class Class source
  Plain text file SQLBuilder.php Class Class source
  Plain text file Table.php Class Class source
  Plain text file Utils.php Class Class source
  Plain text file Validations.php Class Class source

  Files folder image Files (56)  /  core  /  libs  /  classes  /  active_record  /  lib  /  adapters  
File Role Description
  Plain text file MysqlAdapter.php Class Class source
  Plain text file OciAdapter.php Class Class source
  Plain text file PgsqlAdapter.php Class Class source
  Plain text file SqliteAdapter.php Class Class source

  Files folder image Files (56)  /  core  /  libs  /  extras  
File Role Description
  Accessible without login Plain text file class.extras.php Aux. Configuration script

  Files folder image Files (56)  /  core  /  libs  /  framework  
File Role Description
  Plain text file class.action_controller.php Class Class source
  Plain text file class.action_view.php Class Class source
  Plain text file class.dispatcher.php Class Class source
  Plain text file class.router.php Class Class source

  Files folder image Files (56)  /  public  
File Role Description
  Accessible without login Plain text file .htaccess Data Auxiliary data
  Accessible without login HTML file 404.html Doc. Documentation
  Accessible without login Plain text file index.php Aux. Configuration script
  Accessible without login Plain text file nginx-phplightmvc.conf Data Auxiliary data
  Accessible without login Plain text file test.php Aux. Configuration script

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0