- Overview
- Core Framework Classes
- Controller Classes
- Model Classes
- View and Template System
- Plugin System
- Theme System
- Event System
- Authentication & Authorization
- Database Layer
- Utility Classes
- REST API
- Site App Specific APIs
- Examples & Best Practices
Webasyst is an open-source PHP framework for developing multi-user web applications with password-protected backends and publicly available frontends. The framework follows MVC architecture patterns and provides extensive APIs for building scalable web applications.
- Web Server: Apache, nginx, or IIS
- PHP: 7.4+
- PHP Extensions: spl, mbstring, iconv, json, gd or ImageMagick
- Database: MySQL 4.1+
wa-apps/ # Application modules
wa-config/ # Configuration files
wa-content/ # User content and uploads
wa-installer/ # Installation scripts
wa-plugins/ # Plugin modules
wa-system/ # Core framework files
wa-widgets/ # Dashboard widgets
The main system class that provides access to framework functionality.
Returns the singleton instance of the system.
Syntax:
public static function getInstance()Returns: waSystem - The system instance
Example:
$system = waSystem::getInstance();Gets the current application ID.
Syntax:
public function getApp()Returns: string - Current application ID
Example:
$app_id = wa()->getApp();
echo $app_id; // 'site', 'shop', 'blog', etc.Gets the current user object.
Syntax:
public function getUser()Returns: waUser - Current user instance
Example:
$user = wa()->getUser();
if ($user->isAuth()) {
echo "User ID: " . $user->getId();
}Gets the storage handler for the current domain.
Syntax:
public function getStorage()Returns: waStorage - Storage instance
Example:
$storage = wa()->getStorage();
$storage->set('key', 'value');
$value = $storage->get('key');Configuration management class.
Gets a configuration value.
Syntax:
public function get($name, $default = null)Parameters:
$name(string): Configuration key$default(mixed): Default value if key not found
Returns: mixed - Configuration value
Example:
$config = wa()->getConfig();
$debug = $config->get('debug', false);
$db_settings = $config->get('db');HTTP request handling class.
Gets GET parameter value.
Syntax:
public function get($name = null, $default = null, $type = null)Parameters:
$name(string): Parameter name$default(mixed): Default value$type(string): Type casting ('int', 'string', 'array')
Returns: mixed - Parameter value
Example:
$request = waRequest::getInstance();
$page = $request->get('page', 1, 'int');
$search = $request->get('q', '', 'string');Gets POST parameter value.
Syntax:
public function post($name = null, $default = null, $type = null)Example:
$data = $request->post('data', array(), 'array');
$email = $request->post('email', '', 'string');Gets REQUEST parameter value (GET or POST).
Syntax:
public function request($name = null, $default = null, $type = null)HTTP response handling class.
Performs HTTP redirect.
Syntax:
public function redirect($url, $code = 302)Parameters:
$url(string): Redirect URL$code(int): HTTP status code
Example:
$response = waResponse::getInstance();
$response->redirect('/success/');
$response->redirect('https://example.com', 301);Sends JSON response.
Syntax:
public function json($data, $code = 200)Parameters:
$data(mixed): Data to encode as JSON$code(int): HTTP status code
Example:
$response->json(array(
'status' => 'ok',
'data' => $result
));Base controller class for all application controllers.
Gets the current user.
Syntax:
protected function getUser()Returns: waUser - Current user instance
Gets the request object.
Syntax:
protected function getRequest()Returns: waRequest - Request instance
Gets the response object.
Syntax:
protected function getResponse()Returns: waResponse - Response instance
Example Controller:
class myappFrontendController extends waController
{
public function execute()
{
$user = $this->getUser();
$request = $this->getRequest();
$data = array(
'user_id' => $user->getId(),
'search' => $request->get('q', '')
);
$this->view->assign($data);
}
}Controller for rendering views with templates.
Template engine instance.
Type: waSmarty
Example:
class myappPageController extends waViewController
{
public function execute()
{
$this->view->assign('title', 'Page Title');
$this->view->assign('content', 'Page content');
}
}Controller for JSON API responses.
Sends JSON response.
Syntax:
protected function response($data = true, $code = 200)Example:
class myappApiController extends waJsonController
{
public function execute()
{
try {
$data = $this->processRequest();
$this->response($data);
} catch (Exception $e) {
$this->errors = $e->getMessage();
}
}
}Controller for long-running operations with progress tracking.
Marks the operation as complete.
Syntax:
protected function complete($result = true)Updates operation progress.
Syntax:
protected function setProgress($progress, $stage = null)Parameters:
$progress(float): Progress percentage (0-1)$stage(string): Current stage description
Example:
class myappImportController extends waLongActionController
{
public function execute()
{
$total = 1000;
for ($i = 0; $i < $total; $i++) {
// Process item
$this->processItem($i);
// Update progress
$progress = ($i + 1) / $total;
$this->setProgress($progress, "Processing item " . ($i + 1));
if ($this->getRequest()->post('cleanup')) {
break;
}
}
$this->complete('Import completed');
}
}Base model class for database operations.
Constructor.
Syntax:
public function __construct($table = null, $id = null)Parameters:
$table(string): Table name$id(string): Primary key field name
Executes SELECT query.
Syntax:
public function select($fields = '*')Parameters:
$fields(string): Fields to select
Returns: waDbResultSelect - Query result
Example:
class myappProductModel extends waModel
{
protected $table = 'myapp_product';
public function getActive()
{
return $this->select('*')->where('status = ?', 'active')->fetchAll();
}
public function getById($id)
{
return $this->getById($id);
}
}Inserts new record.
Syntax:
public function insert($data, $type = 0)Parameters:
$data(array): Data to insert$type(int): Insert type (0 = INSERT, 1 = REPLACE, 2 = IGNORE)
Returns: mixed - Insert ID or false
Example:
$model = new myappProductModel();
$id = $model->insert(array(
'name' => 'Product Name',
'price' => 99.99,
'status' => 'active'
));Updates record by ID.
Syntax:
public function updateById($id, $data)Parameters:
$id(mixed): Record ID$data(array): Data to update
Returns: int - Number of affected rows
Example:
$model->updateById(123, array(
'name' => 'Updated Name',
'price' => 149.99
));Deletes record by ID.
Syntax:
public function deleteById($id)Parameters:
$id(mixed): Record ID
Returns: int - Number of affected rows
Model for managing contacts/users.
Gets contact by ID.
Syntax:
public function getById($id)Returns: array - Contact data
Searches contacts.
Syntax:
public function search($query, $options = array())Parameters:
$query(string): Search query$options(array): Search options
Example:
$contact_model = new waContactModel();
$contacts = $contact_model->search('john', array(
'limit' => 10,
'offset' => 0
));Smarty template engine wrapper.
Assigns variable to template.
Syntax:
public function assign($var, $value = null)Parameters:
$var(string|array): Variable name or array of variables$value(mixed): Variable value
Example:
$this->view->assign('title', 'Page Title');
$this->view->assign(array(
'products' => $products,
'categories' => $categories
));Renders template and returns output.
Syntax:
public function fetch($template)Parameters:
$template(string): Template path
Returns: string - Rendered output
Example:
$html = $this->view->fetch('product.html');Generates application URL.
Syntax:
{wa_url action="action" param1="value1"}Example:
<a href="{wa_url action='edit' id=$product.id}">Edit</a>Gets current user object.
Example:
{if $wa->user()->isAuth()}
Welcome, {$wa->user()->getName()}!
{/if}Gets current application ID.
Example:
{if $wa->app() == 'shop'}
This is Shop-Script
{/if}Base plugin class.
Gets plugin settings.
Syntax:
public function getSettings($name = null)Parameters:
$name(string): Setting name (optional)
Returns: mixed - Setting value or all settings
Saves plugin settings.
Syntax:
public function saveSettings($settings)Parameters:
$settings(array): Settings to save
class myappMypluginPlugin extends waPlugin
{
public function init()
{
// Plugin initialization
}
public function getSettings($name = null)
{
return parent::getSettings($name);
}
public function backendMenu()
{
// Add backend menu items
return array(
array(
'name' => 'My Plugin',
'url' => '?plugin=myplugin'
)
);
}
}return array(
'name' => 'My Plugin',
'description' => 'Plugin description',
'version' => '1.0.0',
'vendor' => 'Developer Name',
'frontend' => true,
'handlers' => array(
'backend_menu' => 'backendMenu',
'order_action.complete' => 'orderComplete'
)
);themes/
mytheme/
theme.xml # Theme configuration
index.html # Main template
page.html # Page template
css/ # Stylesheets
js/ # JavaScript files
img/ # Images
<?xml version="1.0" encoding="utf-8"?>
<theme id="mytheme" app="site">
<name>My Theme</name>
<description>Theme description</description>
<version>1.0.0</version>
<vendor>Developer Name</vendor>
<files>
<file path="css/style.css">
<description>Main stylesheet</description>
</file>
</files>
<settings>
<setting var="color" title="Primary Color" type="color" value="#007cba"/>
<setting var="logo" title="Logo" type="file" value=""/>
</settings>
</theme>Gets theme URL.
Example:
<link rel="stylesheet" href="{$wa_theme_url}css/style.css">Gets theme file system path.
<style>
body {
background-color: {$wa_theme_settings.color};
}
</style>Event handling system.
Triggers an event.
Syntax:
public static function trigger($event, &$params = null)Parameters:
$event(string): Event name$params(mixed): Event parameters (passed by reference)
Returns: array - Results from event handlers
Example:
$params = array('order_id' => 123);
$results = wa()->event('order.complete', $params);In plugin configuration:
'handlers' => array(
'order.complete' => 'orderComplete',
'product.save' => 'productSave'
)Plugin handler method:
public function orderComplete($params)
{
$order_id = $params['order_id'];
// Handle order completion
return array('processed' => true);
}User management and authentication.
Checks if user is authenticated.
Syntax:
public function isAuth()Returns: bool - True if authenticated
Gets user ID.
Syntax:
public function getId()Returns: int - User ID or null
Gets user display name.
Syntax:
public function getName()Returns: string - User name
Gets user email.
Syntax:
public function getEmail()Returns: string - User email
Gets user rights for application.
Syntax:
public function getRights($app_id, $name = null)Parameters:
$app_id(string): Application ID$name(string): Specific right name
Returns: mixed - Rights data
Example:
$user = wa()->getUser();
// Check authentication
if (!$user->isAuth()) {
throw new waRightsException('Authentication required');
}
// Check specific rights
if (!$user->getRights('myapp', 'edit')) {
throw new waRightsException('Access denied');
}
// Get user info
$user_data = array(
'id' => $user->getId(),
'name' => $user->getName(),
'email' => $user->getEmail()
);Authentication helper.
Authenticates user.
Syntax:
public static function auth($contact_id, $remember = false)Parameters:
$contact_id(int): Contact ID to authenticate$remember(bool): Whether to remember user
Logs out current user.
Syntax:
public static function logout()Database adapter for executing queries.
Executes SQL query.
Syntax:
public function query($sql, $params = null)Parameters:
$sql(string): SQL query$params(array): Query parameters
Returns: resource - Query result
Executes SELECT query and returns all rows.
Syntax:
public function select($sql, $params = null)Returns: array - Result rows
Example:
$db = wa()->getModel()->getAdapter();
// Simple select
$products = $db->select("SELECT * FROM products WHERE status = ?", array('active'));
// Using model
$model = new waModel('products');
$products = $model->select('*')->where('status = ?', 'active')->fetchAll();General utility functions.
Formats datetime.
Syntax:
public static function datetime($timestamp, $format = null)Parameters:
$timestamp(int): Unix timestamp$format(string): Date format
Returns: string - Formatted date
Creates text excerpt.
Syntax:
public static function excerpt($text, $length = 100)Parameters:
$text(string): Source text$length(int): Maximum length
Returns: string - Text excerpt
Example:
$excerpt = waUtils::excerpt($long_text, 200);
$date = waUtils::datetime(time(), 'Y-m-d H:i:s');File system utilities.
Creates directory.
Syntax:
public static function create($path)Deletes file or directory.
Syntax:
public static function delete($path)Copies file or directory.
Syntax:
public static function copy($source, $target)Example:
// Create directory
waFiles::create(wa()->getDataPath('uploads'));
// Copy file
waFiles::copy($source_file, $target_file);
// Delete file
waFiles::delete($old_file);Webasyst provides RESTful API endpoints for accessing application data.
API uses token-based authentication:
GET /api.php/app/method?access_token=TOKEN
POST /api.php/app/method
Authorization: Bearer TOKEN
Gets contacts list.
Parameters:
limit(int): Number of recordsoffset(int): Records offsetfields(string): Comma-separated field list
Response:
{
"data": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
],
"total": 100
}Gets contact by ID.
Response:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"create_datetime": "2023-01-01 10:00:00"
}Creates new contact.
Request Body:
{
"name": "Jane Doe",
"email": "jane@example.com"
}Response:
{
"id": 2,
"name": "Jane Doe",
"email": "jane@example.com"
}Creating custom API methods:
class myappApiController extends waJsonController
{
public function customAction()
{
$data = $this->processCustomLogic();
$this->response($data);
}
}Access via: GET /api.php/myapp/custom
The Site app manages routing and page rendering.
Routing configuration and URL generation.
Generates URL for route.
Syntax:
public static function getUrl($route, $params = array(), $domain = null)Parameters:
$route(string): Route pattern$params(array): Route parameters$domain(string): Domain name
Example:
$url = waRouting::getUrl('frontend/page', array('url' => 'about'));Model for managing site pages.
Methods:
Gets page by URL.
Syntax:
public function getByUrl($url, $domain_id = null)Parameters:
$url(string): Page URL$domain_id(int): Domain ID
Returns: array - Page data
Example:
$page_model = new sitePageModel();
$page = $page_model->getByUrl('about-us');
if ($page) {
echo $page['title'];
echo $page['content'];
}Creates new page.
Syntax:
public function add($data)Parameters:
$data(array): Page data
Example:
$page_id = $page_model->add(array(
'name' => 'About Us',
'title' => 'About Our Company',
'content' => '<p>Page content here...</p>',
'url' => 'about-us',
'status' => 1
));Model for managing domains.
Methods:
Gets domain by name.
Syntax:
public function getByName($name)Example:
$domain_model = new siteDomainModel();
$domain = $domain_model->getByName('example.com');Theme management utilities.
Methods:
Gets theme information.
Syntax:
public static function get($theme_id)Applies theme to domain.
Syntax:
public static function apply($theme_id, $domain_id)Example:
// Get available themes
$themes = siteTheme::getList();
// Apply theme
siteTheme::apply('mytheme', $domain_id);myapp/
lib/
config/
app.php # App configuration
install.php # Installation script
myappConfig.class.php
actions/
backend/
BackendIndex.action.php
frontend/
Index.action.php
templates/
actions/
backend/
BackendIndex.html
Index.html
return array(
'name' => 'My App',
'description' => 'My custom application',
'version' => '1.0.0',
'vendor' => 'My Company',
'frontend' => true,
'backend' => true,
'icon' => array(
48 => 'img/icon48.png'
)
);<?php
class myappIndexAction extends waViewAction
{
public function execute()
{
$model = new myappItemModel();
$items = $model->getAll();
$this->view->assign('items', $items);
$this->setTitle('My App');
}
}<?php
class myappBackendIndexAction extends waViewAction
{
public function execute()
{
// Check user rights
if (!wa()->getUser()->getRights('myapp', 'backend')) {
throw new waRightsException('Access denied');
}
$model = new myappItemModel();
$items = $model->getAll();
$this->view->assign(array(
'items' => $items,
'can_edit' => wa()->getUser()->getRights('myapp', 'edit')
));
}
}<?php
class myappItemModel extends waModel
{
protected $table = 'myapp_item';
protected $id = 'id';
public function getAll($status = 'active')
{
return $this->select('*')
->where('status = ?', $status)
->order('create_datetime DESC')
->fetchAll();
}
public function getPublished()
{
return $this->getAll('published');
}
public function add($data)
{
$data['create_datetime'] = date('Y-m-d H:i:s');
return $this->insert($data);
}
}<div class="myapp-items">
<h1>My App Items</h1>
{foreach $items as $item}
<div class="item">
<h2>{$item.title|escape}</h2>
<p>{$item.description|escape}</p>
<small>Created: {$item.create_datetime|wa_datetime}</small>
</div>
{/foreach}
</div><?php
class myappApiSaveController extends waJsonController
{
public function execute()
{
try {
// Validate input
$data = $this->getRequest()->post('data');
if (empty($data['title'])) {
throw new waException('Title is required');
}
// Save data
$model = new myappItemModel();
$id = $model->add($data);
$this->response(array(
'id' => $id,
'message' => 'Item saved successfully'
));
} catch (Exception $e) {
$this->setError($e->getMessage());
}
}
}<?php
class myappMypluginPlugin extends waPlugin
{
public function orderComplete($params)
{
$order_id = $params['order_id'];
// Send notification email
$this->sendNotification($order_id);
return array('status' => 'notification_sent');
}
private function sendNotification($order_id)
{
$settings = $this->getSettings();
if ($settings['notifications_enabled']) {
// Send email logic here
}
}
public function backendMenu()
{
return array(
'name' => 'My Plugin',
'url' => wa()->getAppUrl('myapp') . '?plugin=myplugin',
'icon' => 'icon.png'
);
}
}// Always validate and sanitize input
$email = $request->post('email', '', 'string');
if (!wa()->getValidator('email')->isValid($email)) {
throw new waException('Invalid email');
}
// Check user rights
if (!wa()->getUser()->getRights('myapp', 'edit')) {
throw new waRightsException('Access denied');
}
// Use prepared statements
$items = $model->select('*')->where('user_id = ?', $user_id)->fetchAll();try {
$result = $this->processData();
$this->response($result);
} catch (waException $e) {
$this->setError($e->getMessage());
} catch (Exception $e) {
waLog::log($e->getMessage(), 'myapp/error.log');
$this->setError('An error occurred');
}$cache = wa()->getCache();
$key = 'myapp_items_' . $user_id;
$items = $cache->get($key);
if ($items === null) {
$items = $model->getByUserId($user_id);
$cache->set($key, $items, 3600); // Cache for 1 hour
}// In PHP code
$message = _w('Item saved successfully');
// In templates
{"Item saved successfully"|_w}
// With parameters
{sprintf(_w('Found %d items'), $count)}// Application logs
waLog::log('User action performed', 'myapp/user.log');
// Error logs
waLog::log($exception->getMessage(), 'myapp/error.log');
// Debug logs (only in debug mode)
waLog::debug($debug_data, 'myapp/debug.log');This comprehensive documentation covers the main APIs, classes, and components of the Webasyst framework with practical examples and usage patterns. For more specific implementation details, refer to the framework source code and official documentation at developers.webasyst.com.