-
Notifications
You must be signed in to change notification settings - Fork 0
07_Database
Before using the Database
class, make sure to configure the environment variables correctly in your .env
file.
APP_NAME="SyntoraPHP"
APP_DEBUG=true
# Database Connection
DB_HOST=localhost
DB_PORT=3306
DB_NAME=syntora
DB_USER=root
DB_PASSWORD=
The database model in App/Models/Database.php
uses Medoo as the database connection layer. Below is the basic implementation of the Database
class:
<?php
namespace SyntoraPHP\App\Models;
use Medoo\Medoo;
class Database
{
public function connect() {
$env = new Env('.env');
$database = new Medoo([
'type' => 'mysql',
'host' => $env->get('DB_HOST'),
'database' => $env->get('DB_NAME'),
'username' => $env->get('DB_USER'),
'password' => $env->get('DB_PASSWORD'),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'port' => $env->get('DB_PORT'),
]);
return $database;
}
}
To use the database connection, you can simply call the connect()
method and then perform queries using Medoo methods:
$database = (new SyntoraPHP\App\Models\Database())->connect();
// Example: Fetch all users
$users = $database->select('users', '*');
// Example: Insert a new user
$database->insert('users', [
'name' => 'John Doe',
'email' => 'john@example.com',
]);
// Example: Update user by ID
$database->update('users', [
'email' => 'newemail@example.com'
], [
'id' => 1
]);
// Example: Delete a user by ID
$database->delete('users', ['id' => 1]);
For more detailed information on Medoo's methods, you can refer to the official Medoo Documentation.
Here’s an example controller located in App/Controllers/UserController.php
. It handles the basic CRUD operations for the /users
route.
<?php
namespace SyntoraPHP\App\Controllers;
class UserController
{
public function index()
{
// Handle GET request to /users
}
public function store()
{
// Handle POST request to /users
}
public function update($id)
{
// Handle PUT request to /users/{id}
}
public function delete($id)
{
// Handle DELETE request to /users/{id}
}
}
Define your routes in routes/web.php
as shown below. The Route
class handles different HTTP methods and maps them to controllers or closures.
<?php
use SyntoraPHP\App\Route;
Route::get('/', function () {
view("index", [
"title" => "SyntoraPHP"
]);
});
Route::get('/panel', 'PanelController@index');
Route::get('/users', 'UserController@index');
Route::post('/users', 'UserController@store');
Route::put('/users/{id}', 'UserController@update');
Route::delete('/users/{id}', 'UserController@delete');
For more examples of Medoo methods and usage, refer to Medoo Documentation.
- 1 - Installation
- 2 - Routing
- 3 - HTTP Request
- 4 - CORS
- 5 - Environment Variables
- 6 - Views
- 7 - Database
- 1 - Installation
- 2 - Routing
- 3 - HTTP Request
- 4 - CORS
- 5 - Environment Variables
- 6 - Views
- 7 - Database