1. Go to this page and download the library: Download codemystify/wordforge library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
codemystify / wordforge example snippets
use Route;
// Define a simple GET route
Route::get('posts', 'PostController@index');
// Route with parameters
Route::get('posts/{id}', 'PostController@show');
// Route with parameter constraints
Route::get('posts/{year}/{month}', 'PostController@archive')
->where('year', '[0-9]{4}')
->where('month', '[0-9]{1,2}');
// Define a resource route
Route::resource('posts', 'PostController');
// Define an API resource route (no create/edit endpoints)
Route::apiResource('users', 'UserController');
// Named route
Route::get('posts/{slug}', 'PostController@showBySlug')->name('posts.slug');
// Generate URL by route name
$url = Route::url('posts.slug', ['slug' => 'hello-world']);
// Define middleware directly on routes
Route::get('profile', 'ProfileController@show')->middleware('auth');
// You can also pass an array of middleware
Route::get('admin', 'AdminController@index')->middleware(['auth', 'admin']);
/**
* Plugin Name: My WordForge App
* Description: A WordPress plugin powered by WordForge
* Version: 1.0.0
* Author: Your Name
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// Define plugin path
define('MY_PLUGIN_PATH', plugin_dir_path(__FILE__));
// Load Composer autoloader
use WordForge\Support\Facades\Route;
use App\Controllers\UserController;
use App\Controllers\PostController;
// Simple route with a callback
Route::get('hello', function() {
return Response::json([
'message' => 'Hello, WordForge!'
]);
});
Route::get('users/{id}', [UserController::class, 'show']);
// Route group with middleware
Route::group(['middleware' => 'auth'], function() {
Route::post('posts', [PostController::class, 'store']);
Route::put('posts/{id}', [PostController::class, 'update']);
Route::delete('posts/{id}', [PostController::class, 'destroy']);
});
// CORRECT: Use the Route facade
Route::get('test', function() { return ['message' => 'It works!']; });
// INCORRECT: Don't use Router class directly
// Router::get('test', function() { return ['message' => 'It works!']; });
class RouteServiceProvider extends ServiceProvider
{
public function register(): void
{
// Set namespace here
Router::setNamespace($apiPrefix);
}
public function boot(): void
{
// Load routes here
// main-plugin-file.php
ly after autoloading
WordForge::bootstrap(__DIR__);
// For numeric IDs (post_id, user_id, etc.)
Route::get('posts/{id}', [PostController::class, 'show'])
->where('id', '\d+'); // or '[0-9]+'
// For alphanumeric identifiers
Route::get('products/{sku}', [ProductController::class, 'show'])
->where('sku', '[a-zA-Z0-9]+');
// For slugs (letters, numbers, and dashes)
Route::get('categories/{slug}', [CategoryController::class, 'show'])
->where('slug', '[a-z0-9-]+');
// For UUIDs
Route::get('orders/{uuid}', [OrderController::class, 'show'])
->where('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}');
// For dates (YYYY-MM-DD)
Route::get('reports/{date}', [ReportController::class, 'show'])
->where('date', '[0-9]{4}-[0-9]{2}-[0-9]{2}');
// For multiple constraints
Route::get('posts/{category}/{slug}', [PostController::class, 'categoryPost'])
->where([
'category' => '[a-z0-9-]+',
'slug' => '[a-z0-9-]+'
]);
namespace App\Controllers;
use WordForge\Http\Controllers\Controller;
use WordForge\Http\Request;
use WordForge\Database\QueryBuilder;
class UserController extends Controller
{
/**
* Display a listing of users.
*
* @param Request $request
* @return \WordForge\Http\Response
*/
public function index(Request $request)
{
$users = QueryBuilder::table('users')
->select(['ID', 'display_name', 'user_email'])
->get();
return $this->success($users);
}
/**
* Display the specified user.
*
* @param Request $request
* @return \WordForge\Http\Response
*/
public function show(Request $request)
{
$id = $request->param('id');
$user = QueryBuilder::table('users')
->where('ID', $id)
->first();
if (!$user) {
return $this->notFound('User not found');
}
return $this->success($user);
}
}
namespace App\Requests;
use WordForge\Validation\FormRequest;
class CreatePostRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'itle is {
return current_user_can('edit_posts');
}
}
namespace App\Controllers;
use WordForge\Http\Controllers\Controller;
use WordForge\Http\Request;
use App\Requests\CreatePostRequest;
class PostController extends Controller
{
/**
* Store a newly created post.
*
* @param Request $request
* @return \WordForge\Http\Response
*/
public function store(Request $request)
{
// Create and validate the form request
$formRequest = new CreatePostRequest($request->getWordPressRequest());
$validation = $formRequest->validate($formRequest->rules());
// Check if validation failed
if ($validation !== true) {
return $this->validationError($validation);
}
// Get the validated data
$validated = $formRequest->validated($formRequest->rules());
$postId = wp_insert_post([
'post_title' => $validated['title'],
'post_content' => $validated['content'],
'post_status' => $validated['status'],
'post_author' => get_current_user_id(),
]);
if (is_wp_error($postId)) {
return $this->error($postId->get_error_message());
}
return $this->created(['id' => $postId]);
}
}
use WordForge\Database\QueryBuilder;
// Simple select query
$posts = QueryBuilder::table('posts')
->where('post_status', 'publish')
->orderBy('post_date', 'desc')
->limit(10)
->get();
// Complex query with joins
$comments = QueryBuilder::table('comments')
->select(['comments.*', 'posts.post_title'])
->join('posts', 'comments.comment_post_ID', '=', 'posts.ID')
->where('comments.comment_approved', '1')
->orderBy('comments.comment_date', 'desc')
->limit(20)
->get();
// Insert data
$id = QueryBuilder::table('my_custom_table')
->insert([
'name' => 'John Doe',
'email' => '[email protected]',
'created_at' => current_time('mysql')
]);
// Update data
QueryBuilder::table('my_custom_table')
->where('id', 5)
->update([
'name' => 'Jane Doe',
'updated_at' => current_time('mysql')
]);
// Delete data
QueryBuilder::table('my_custom_table')
->where('id', 5)
->delete();
// Transactions
QueryBuilder::table('my_custom_table')->transaction(function($query) {
$query->insert(['name' => 'Transaction 1']);
$query->insert(['name' => 'Transaction 2']);
// If any query fails, all changes will be rolled back
});
namespace App\Middleware;
use WordForge\Http\Middleware\Middleware;
use WordForge\Http\Request;
use WordForge\Support\Facades\Response;
class AdminOnlyMiddleware implements Middleware
{
/**
* Handle the incoming request.
*
* @param Request $request
* @return mixed
*/
public function handle(Request $request)
{
if (!current_user_can('manage_options')) {
return Response::forbidden('This endpoint is for administrators only');
}
return true;
}
}
// Get the current request
$request = wordforge_request();
// Get a specific input value
$name = wordforge_request('name', 'default');
// Create a response
$response = wordforge_response(['data' => 'value'], 200);
// Create a JSON response
$response = wordforge_json(['success' => true]);
// Render a view
echo wordforge_view('admin.settings', ['option' => 'value']);
// Get a configuration value
$apiKey = wordforge_config('services.api.key');
// Generate a URL to a named route
$url = wordforge_url('users.show', ['id' => 1]);
// Generate a URL to an asset
$url = wordforge_asset('js/app.js');
// Get a service from the service manager
$notification = wordforge_service('notification');
// Check if a service exists
if (wordforge_has_service('mailer')) {
$mailer = wordforge_service('mailer');
}
namespace App\Providers;
use WordForge\Support\ServiceProvider;
use App\Services\Mailer;
use App\Services\NotificationService;
class NotificationServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register(): void
{
// Register a mailer service
$this->registerSingleton('mailer', function() {
return new Mailer(
wordforge_config('mail.from'),
wordforge_config('mail.name')
);
});
// Register notification service that depends on mailer
$this->registerSingleton('notification', function() {
// Get the mailer dependency
$mailer = wordforge_service('mailer');
return new NotificationService($mailer);
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Get the notification service
$notification = wordforge_service('notification');
// Register hooks
add_action('user_register', [$notification, 'sendWelcomeEmail']);
add_action('comment_post', [$notification, 'sendCommentNotification'], 10, 2);
}
/**
* Specify which WordPress hooks should trigger this provider
*
* @return array
*/
public function hooks(): array
{
// Run this provider on plugins_loaded with priority 20
return ['plugins_loaded' => 20];
}
}
use WordForge\Support\ServiceManager;
// Register a service
ServiceManager::register('logger', function($channel = 'main') {
return new Logger($channel);
});
// Register a singleton
ServiceManager::singleton('config', function() {
return new ConfigRepository();
});
// Set an instance directly
$cache = new Cache();
ServiceManager::instance('cache', $cache);
// Check if a service exists
if (ServiceManager::has('mailer')) {
// Get a service
$mailer = ServiceManager::get('mailer');
}
namespace App\Rules;
use WordForge\Validation\Rules\Rule;
class IsWordPressAdmin implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes(string $attribute, $value): bool
{
$user = get_user_by('id', $value);
return $user && user_can($user, 'manage_options');
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
return 'The :attribute must be a WordPress administrator.';
}
}
public function rules()
{
return [
'user_id' => ['
// Register and enqueue a script
wp_enqueue_script(
'my-plugin-script',
wordforge_asset('js/app.js'),
['jquery'],
'1.0.0',
true
);
// Generate a URL to a named route
$userEditUrl = wordforge_url('users.edit', ['id' => $user->ID]);
// Get a single config value
$apiKey = wordforge_config('services.mailchimp.api_key');
// Get a config value with default
$analyticsId = wordforge_config('services.google.analytics_id', 'UA-DEFAULT');
// Get all providers
$providers = wordforge_config('app.providers');
// tests/bootstrap.php
work
// tests/Unit/ExampleTest.php
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function testBasicTest()
{
$this->assertTrue(true);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.