Eco is a PHP Framework for PHP 5.5+
Install example:
# wget shayanderson.com/eco.zip
# unzip ./eco.zip
- Routing
- Route Parameters
- Views
- Logging
- Error Handling
- Hooks
- Configuration
- Core Methods
- Core Classes (Cache, Database, Form, HTTP, Model, Table)
- Helper Classes (Benchmark, Breadcrumb, Filter, Flash, Format, Request, Response, Service, Session, Socket, Validate)
- Helper Functions (core, alias, factory, flash, request, response, view)
- Extending Eco
Basic routes can be setup in app/com/route.php
, for example:
// set routes
return [
// class method
'/' => 'IndexController->home',
// namespace
'login' => 'Account\UserController->login',
// callable
'logout' => function() { /* do something */ },
// more routes
];
The request /
would call the method home
in the class IndexController
in file app/mod/IndexController.php
.
The request /login
would call the method login
in the class \Account\UserController
in file app/mod/Account/UserController.php
.
Specific HTTP methods can be used for routes:
eco::route('GET@api/user/:id', function($id) { /* GET method */ });
eco::route('DELETE@api/user/:id', function($id) { /* DELETE method */ });
eco::route('POST@api/user/:id?', function($id = null) { /* POST method */ });
// or handle multiple HTTP methods
eco::route('POST|PUT@api/user/:id?', function($id = null) { /* POST or PUT method */ });
These HTTP methods are supported:
DELETE
,GET
,HEAD
,PATCH
,POST
,PUT
Route callbacks can be a callable name or callable (the first array element must be the controller/action):
function auth() { /* do something */ }
eco::route('account/secure',
['AccountController->secure', 'auth', function() { /* invoked */ }]);
Warning: Route Callbacks do not work with Dynamic Route Setting
Dynamic route setters can be used for larger applications that have many routes (lazy load routes), for example:
eco::route('account*', 'AccountController::getRoutes()');
Now all requests that begin with /account
will load the routes using the method:
class AccountController
{
public static function getRoutes()
{
return [
'account/login' => 'AccountController->login',
// do not have to use class name if in same class:
'account/logout' => 'logout'
];
}
}
Dynamic route setting (lazy load routes) can also be set directly as an array, example:
eco::route('account*', [
'AccountController', // the class name must be first (index:0)
'account/login' => 'login',
'account/logout' => 'logout'
]);
CLI routing is simple to use, for example:
eco:route('bin/test/:id', function($id) {
echo 'CLI test, id: ' . $id;
});
Now a CLI command can be issued:
$ php index.php bin/test/5
Bin test: 5
The above route would also work in a Web browser. To create a CLI only route (will not work in Web browser) add a
$
to the beginning of route, for example:
// this route will only work as CLI command
// the request '/bin/test/5' in a Web browser would result in a 404 error
eco:route('$bin/test/:id', function($id) {
echo 'CLI test, id: ' . $id;
});
Named route parameters:
eco::route('user/:id', 'UserController->view');
The :id
value will be passed to the callable or class method:
class UserController
{
public function view($id)
{
// do something
}
}
Optional parameters can be used:
eco::route('page/:id/:title?', function($id, $title = null) {});
Wildcard parameters example:
eco::route('product/:info+', function($info) {
// if request is '/product/1/abc/x'
// $info is an array: ['1', 'abc', 'x']
});
Route parameter callbacks can be used in several different ways:
eco::route('page/:title:strtoupper', 'PageController->view');
Or set parameter callbacks in array (the first array element must be the class method / callable):
eco::route('page/:title', ['PageController->view', ['title' => 'strtoupper']]);
Also, global route parameter callbacks can be set, for example:
// globally set route param callback
// now every ':id' param will use this callback
// global param callbacks are overwritten by local ones
eco::param('id', function($id) { return strtoupper($id); });
// or use multiple param names:
eco::param(['x', 'y', 'z'], function($val) { });
Route callbacks can also be used with route parameter callbacks:
eco::route('page/:title', [
'PageController->view',
'route_callback',
function() { /* route callback */ },
// route param callback
['title' => 'strtoupper']
]);
Route parameter regular expressions can be used, if the match fails the route will not be invoked:
eco::route('user/:id@[0-9]+', ...);
The order of syntax matters when using different types of parameters and/or combining callbacks and regular expressions, here is the correct syntax:
// when using callback with regular expression
// the callback must come first:
eco::route('user/:id:strtoupper@[0-9]+', ...);
// use optional param and callback:
eco::route('user/:id/:name?:strtoupper', ...);
// use optional param and regular expression:
eco::route('user/:id/:name?@[a-z]+', ...);
// use optional param, callback and regular expression:
eco::route('user/:id/:name?:strtoupper@[a-z]+', ...);
// use wildcard param and callback:
eco::route('user/:params+:strtoupper', ...);
// use wildcard param and regular expression:
eco::route('user/:params+@[a-z]+', ...);
// use wildcard param, callback and regular expression:
eco::route('user/:params+:strtoupper@[a-z]+', ...);
The view object can be used in a route actions:
class PageController
{
public function get($id)
{
$page = PageModel::get($id);
// set view param
eco::view()->set('title', $page->title);
// or use view() helper function
// view()->set('title', $page->title);
// or like this:
view()->author = $page->author;
// load template file 'page/view'
// and can also set view param 'content'
view('page/view', [
'content' => $page->content
]);
}
}
Route parameters can also be accessed using
Router
class methods.
The app/tpl/page/view.tpl
file example:
<?php include PATH_TEMPLATE_GLOBAL . 'header.tpl'; ?>
<h1><?=$title?></h1>
<p>Author: <?=$author?></p>
<?=$content?>
<?php include PATH_TEMPLATE_GLOBAL . 'footer.tpl'; ?>
Logging messages example:
eco::log()->error('Bad error / fatal');
eco::log()->warning('Warning conditions');
eco::log()->notice('Notice message');
eco::log()->debug('File has loaded');
Categories can be used when logging a message:
// category 'payment'
eco::log()->error('Failed to access payment gateway', 'payment');
Debugging info can also be added:
eco::log()->warning('Request failed', /* category optional */ null,
['request' => 'x', 'client' => 'y']);
Get entire log:
$log = eco::log()->get();
Setup custom log handler example:
eco::log()->setHandler(function($message, $level, $category, $info){
// if sending message to database
// do no send if database connection error, example:
// if(substr($message, 0, 17) == 'SQLSTATE[HY000] [')
// {
// return false;
// }
// handle custom logging
return true; // handled
});
If the custom log handler callable does not return
true
the internal logger will continue as normal
Trigger error examples:
eco::error('Error message');
// or use helper function
error('Something bad');
// custom error code
error('Page not found', 404);
// add log category
error('Failed to load user', null, 'account');
// by default the HTTP error response code is sent
// to not send HTTP code use:
error('Page not found', 404, 'category' false);
The last error message (and error category) sent to the eco::error()
function can be accessed using:
$error_message = eco::errorGetLast();
$error_category = eco::errorGetLastCategory();
A 404 callback can be used to handle the 404 before an error is called
Hooks can be used to load files or use callbacks during execution, examples:
// called before routing starts
eco::hook(eco::HOOK_BEFORE, function() { /* do something */ });
// called before the route callable or class method is called
// include a file example:
eco::hook(eco::HOOK_MIDDLE, PATH_LIB . 'hook/middle.php');
// called after dispatching
eco::hook(eco::HOOK_AFTER, function() { /* do something */ });
Application and Eco configuration settings are handled separately.
The Eco configuration settings file is located at app/com/conf/eco.conf.php
and contains all framework settings. All documentation for Eco configuration settings can be found in the file.
Application configuration settings can be stored by Eco, example:
// load config file(s) using path
eco::conf(PATH_CONF . 'app.conf.php');
eco::conf(PATH_CONF . 'api.conf.php');
// or load config settings using array
eco::conf(['local' => ['path' => 'x', 'filename' => 'y']]);
// use config settings
$app_username = eco::conf()->app->username;
$local_path = eco::conf()->local->path;
The configuration files must return an array, app.conf.php
example:
return [
'app' => [
'username' => 'x',
'password' => 'y'
],
'core' => [ /* more */ ]
];
Configuration settings cannot be overwritten when using multiple files, so the primary array keys must be unique even in different files. Never use the primary array key
_eco
which is used by Eco for internal framework settings.
Configuration settings can also be used separately from Eco, for example:
// do not store internally
$conf = eco::conf(PATH_CONF . 'app.conf.php', false);
// use config settings
$app_username = $conf->app->username;
Eco offers the following methods:
eco::autoload($paths)
- class autoloadereco::breadcrumb()
- access Breadcrumb class (breadcrumb()
helper function available)eco::clear($key)
- clear global variableeco::conf($file_path, $store)
- register / load application configuration settings file (conf()
helper function available)eco::db($connection_id)
- access Database class (db()
helper function available)eco::error($message, $code, $category, $http_response_code)
- trigger an error (error()
helper function available)eco::filter()
- access data Filter class (filter()
helper function available)eco::flash()
- access session Flash class (flash()
helper function available)eco::format()
- access data Format class (format()
helper function available)eco::get($key)
- get a global variableeco::has($key)
- check if a global variable existseco::hook($name, $callback)
- add a hookeco::log()
- access Log class (logger()
helper function available)eco::model()
- Model class loader (model()
helper function available)eco::param($id, $callback)
- map route parameter callback (param()
helper function available)eco::request()
- access Request class (request()
helper function available)eco::response()
- access Response class (response()
helper function available)eco::route($route, $action)
- map routeeco::router()
- access core Router classeco::run()
- run the applicationeco::service()
- Service class loader (service()
helper function available)eco::session()
- access Session class (session()
helper function available)eco::set($key, $value)
- set a global variableeco::stop()
- gracefully stop the application (stop()
helper function available)eco::validate()
- access data Validate class (validate()
helper function available)eco::view($template, $view_params)
- load view template file and access View class (view()
helper function available)
Core classes can be used to simplify common application tasks:
Eco\Cache
- Server-side cache core classEco\Database
- Database core classEco\Form
- HTML form core classEco\Http
- HTTP request core classEco\Model
- Database model core classEco\Table
- HTML table core class
These helper classes are available:
Eco\Benchmark
- benchmarking helperEco\System\Breadcrumb
- access witheco::breadcrumb()
orbreadcrumb()
helper functionEco\System\Filter
- access witheco::filter()
orfilter()
helper functionEco\System\Session\Flash
- access witheco::flash()
orflash()
helper functionEco\System\Format
- access witheco::format()
orformat()
helper functionEco\System\Request
- access witheco::request()
orrequest()
helper functionEco\System\Registry\Service
- access witheco::service()
orservice()
helper functionEco\System\Session
- access witheco::session()
orsession()
helper function\Eco\Socket\Client
and\Eco\Socket\Server
- creating sockets helpersEco\System\Validate
- acccess witheco::validate()
orvalidate()
helper function
Helper functions can be used to quickly access Eco core methods or other useful functionality. Find helper functions documentation here.
Eco can be extended by extending the core Eco\System
class. Initially this is setup in the app/com/bootstrap.php
file:
// set Eco access class
class eco extends \Eco\System {}
The extending class can be used to add methods or override Eco\System
overridable methods.