Sturdy is a web application microframework adopting Model-View-Controller design pattern inspired by Django. It features database abstraction, URL routing and dispatching, cookie based messages, and templating.
Any contribution or feedback is welcome.
All requests are directed to index.php (specified in .htaccess) where the page is constructed by matching the requested url to the app's urls specified in urls.php and by calling the corresponding view function.
Model classes represent database tables, and their instances database records. After they are created in models.php, the corresponding database table needs to be created manually.
A model representing an user is used for demonstration in this document.
class User extends Model{
public $id; //
public $email; //
public $password; //
public $firstName; //
public $lastName; // database fields as class properties as they appear in the database
function fullName(){ //utility methods can be created
return $this->firstName." ".$this->lastName;
}
}
$newUser = new User();
$newUser->email = "newuser@example.com";
$newUser->firstName = "new";
$newUser->lastName = "user";
$newUser->save(); //it's now in the database!
$user = User::get("email = newuser@example.com");
//do whatever you'd like, such as changing a field:
$user->email = "newmail@example.com";
$user->save();
$users = User::filter("firstName = 'John'"); //all users with the name john
$users = User::all(); //all users
if(User::exists("email = test@example.com"){
//do things
}
Delete specific object
$user->delete();
Delete one or more
User::deleteWhere("id > 3");
A view represents a page that is rendered or an action like logging out. It processes data and passes them to templates or redirects to another view. Templates contain html and may render php variables passed to them.
Views are functions in views.php. They also need to be added to the urls array in urls.php:
$urls = [
//...
"pathToView" => "nameOfView"
];
This record defines a view that is served on /pathToview
by the function nameOfView
.
function ourNewView(){
$context = [
//this array is for data that will be used in the template
"fruit" => "apple",
"color" => "green
];
render("ourNewTemplate.php", $context)
//or if you're not passing variables:
render("ourNewTemplate.php");
}
function ourNewView(){
//do some business stuff
header("Location: /"); //redirect home
}
Cookie based messages that can be retrieved from different views after redirecting.
require "sturdy/messages.php";
addMessage("success", "This is a success message.");
$messages = getMessages();
Upon retrieving, messages are deleted.
<?php foreach($messages as $message): ?>
<div class="<?= $message["level"] ?>">
<p><?= $message["body"] ?></p>
</div>
<?php endforeach ?>