Get started with ZenithPHP, a lightweight and flexible PHP framework designed for ease of use and rapid development. Ideal for developers seeking simplicity and efficiency, ZenithPHP offers a clean, intuitive structure for building MVC applications. Learn more about the framework to explore its core features and components.
Download ZenithPHPTo get started with ZenithPHP, clone the framework repository from GitHub to your local environment.
git clone
https://github.com/ZenithPHP-Framework/full-zenith-framework.git
Once cloned, navigate to the project folder and install the necessary dependencies using Composer.
cd full-zenith-framework
composer install
Copy the example environment file to set up your environment variables. Configure database credentials and other necessary settings.
cp .env.example .env
Open the .env
file and update it with your
specific configuration values.
To run the application locally, start the built-in development server using the command below.
php cli run
Visit http://localhost:8000 in your browser to view the landing page.
To create a controller in ZenithPHP, use the following command:
php cli make:controller WelcomeController
This command will create a new file named
WelcomeController.php
in the
App/Controllers
directory. You can define
your controller’s actions here.
<?php
namespace App\Controllers;
use ZenithPHP\Core\Controller\Controller;
use ZenithPHP\Core\Http\Request;
use ZenithPHP\Core\Http\Response;
class WelcomeController extends Controller
{
public function index(Request $request, Response $response)
{
// Load a view file
$this->view('welcome');
}
}
?>
In the App/routes.php
file, configure routes
for your controller methods.
use ZenithPHP\Core\Http\Router;
// Define a route to your controller’s action
Router::get('/welcome', 'WelcomeController', 'index');
To create a new model, use the command below:
php cli make:model User
This command generates a User.php
file in the
App/Models
directory. Define the model's
properties and relationships within this file.
<?php
namespace App\Models;
use ZenithPHP\Core\Database\Model;
class User extends Model
{
protected $table = 'users';
}
?>
To set up database tables, you can create migrations. Use the command:
php cli make:migration users
Save your migration files in the
Migrations
folder. Each migration should
extend the Migration
class.
<?php
use ZenithPHP\Core\Database\Migration;
use ZenithPHP\Core\Database\Schema;
class _2024_10_27_174853_users extends Migration
{
public function up()
{
Schema::create('users', function (Schema $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
?>
ZenithPHP makes it easy to create APIs for your application. Follow these steps to create a simple API that retrieves user data.
Start by creating a new route in the App/routes.php
file. This route will map the API
endpoint to a specific controller action.
use ZenithPHP\Core\Http\Router;
Router::get('/api/users', 'UserController', 'index');
Use the CLI tool to create a new model for your API. This model will handle data interaction with the database.
php cli make:model User
In the generated User
model, define the database table name to interact with. Here’s an
example:
use ZenithPHP\Core\Model\Model;
class User extends Model
{
protected string $table_name = 'users';
}
Next, create a controller that will fetch data from the User
model and return it as
JSON. Use the CLI tool to generate this controller.
php cli make:controller UserController
In the UserController
, define the index
method to handle incoming
requests, fetch data from the User
model, and return it as a JSON response.
use ZenithPHP\Core\Controller\Controller;
use ZenithPHP\Core\Http\Response;
use ZenithPHP\Core\Http\Request;
use ZenithPHP\App\Models\User;
class UserController extends Controller
{
public function index(Request $request, Response $response)
{
$user = new User($this->pdo);
$allUsers = $user->getAll();
$response->json(['status' => 'success', 'data' => $allUsers]);
}
}
Once everything is set up, you can access the API by visiting
http://localhost:8000/api/users
in your browser. This should return a JSON response
with user data.
{
"status": "success",
"data": [
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "janesmith@example.com"
}
]
}
This simple example demonstrates how you can set up an API in ZenithPHP to serve JSON data. You can create additional routes and methods to handle other data interactions and enhance your API functionality.
Middleware in ZenithPHP enables you to apply logic before or after a request is processed. This functionality is helpful for enforcing access controls, logging requests, or modifying requests and responses.
For instance, the AuthMiddleware
can restrict access based on authentication or
specific user roles. You can define middleware classes to manage various tasks, such as ensuring
that users are authenticated or have a specific role before accessing certain routes.
To create a middleware, define a class in the App\Middleware
namespace and extend the
base Middleware
class. Middleware classes contain a handle
method that
checks the request and response, performs any necessary logic, and optionally calls the
$next
function to continue processing the request.
namespace ZenithPHP\App\Middleware;
use ZenithPHP\Core\Http\Request;
use ZenithPHP\Core\Http\Response;
use ZenithPHP\Core\Middleware\Middleware;
class AuthMiddleware extends Middleware
{
protected string $role;
public function __construct(string $role = '')
{
$this->role = $role;
}
public function handle(Request $request, Response $response, callable $next)
{
session_start();
$user = $_SESSION['user'] ?? null;
if ($this->role && (!$user || $user['role'] !== $this->role)) {
$response->send("Unauthorized", 403);
exit();
}
if (!$user && $this->role === '') {
$response->send("Please login", 401);
exit();
}
// Call the next middleware or controller action
return $next($request, $response);
}
}
Once you've defined a middleware class, you can apply it to routes to enforce specific access rules.
In the example below, the auth
middleware restricts access to authenticated users,
while auth:admin
restricts it to users with an "admin" role.
Router::get('/dashboard', 'DashboardController', 'index')->only('auth');
Router::get('/admin', 'AdminController', 'index')->only('auth:admin');
These routes will only be accessible to users who meet the specified middleware requirements, ensuring secure access control and reducing the risk of unauthorized access.
The Pluto template engine in ZenithPHP allows you to easily build dynamic views with clean and readable syntax. It’s designed to simplify templating and enhance the readability of your views, using special tags for logic and variables.
Pluto introduces a set of custom tags and directives that allow you to insert dynamic data, control the flow, and loop through data collections. Here’s a quick overview:
<< $variable >>
to output PHP
variables in the view.@if
, @elseif
,
@else
, and @endif
directives for conditional rendering.
@foreach
and @endforeach
to iterate over
collections.@php
and @endphp
to include raw PHP
code.@section
and @yield
for
layout management.<< // comment text >>
for comments.
<!-- Displaying a variable -->
<< $username >>
<!-- Conditional Statement -->
@if ($userRole == 'admin')
<p>Welcome, Admin!</p>
@elseif ($userRole == 'member')
<p>Welcome, Member!</p>
@else
<p>Welcome, Guest!</p>
@endif
<!-- Looping Through Data -->
@foreach ($items as $item)
<p><< $item->name >> - << $item->price >></p>
@endforeach
<!-- Using PHP Code -->
@php
$count = count($items);
@endphp
Total items: << $count >>
<!-- Defining Sections and Yields -->
@section('content')
<p>This is the main content area.</p>
@endsection
@yield('content') <!-- Where the content will be injected -->
<!-- Pluto Comment -->
<< // This is a comment that won't be rendered >>
To create a new view using the Pluto template engine, follow these steps:
home.pluto.php
(you can replace
home
with your desired filename).To render a view using Pluto, specify the path to the template file. The engine will automatically parse the Pluto syntax and render the final HTML.
class HomeController extends Controller
{
public function index(Request $request, Response $response)
{
return view('home', [
'username' => 'John Doe',
'userRole' => 'admin',
'items' => [
(object) ['name' => 'Laptop', 'price' => '$999'],
(object) ['name' => 'Smartphone', 'price' => '$499'],
]
]);
}
}
With Pluto, you can keep logic out of your views, making them cleaner and more maintainable. It provides a straightforward syntax for working with dynamic data and helps developers create well-structured and easily understandable templates.