Skip to content

shayanderson/eco

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

94 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Eco Framework

Eco is a PHP Framework for PHP 5.5+

Install example:

# wget shayanderson.com/eco.zip
# unzip ./eco.zip

Documentation Topics

Routing

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.

HTTP Methods

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

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 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

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;
});

Route Parameters

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

Optional parameters can be used:

eco::route('page/:id/:title?', function($id, $title = null) {});

Wildcard Parameters

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

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

Route parameter regular expressions can be used, if the match fails the route will not be invoked:

eco::route('user/:id@[0-9]+', ...);

Route Parameter Syntax

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]+', ...);

Views

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.

View Template

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

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

Error Handling

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

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 */ });

Configuration

Application and Eco configuration settings are handled separately.

Eco Configuration

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

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;

Core Methods

Eco offers the following methods:

Core Classes

Core classes can be used to simplify common application tasks:

Helper Classes

These helper classes are available:

Helper Functions

Helper functions can be used to quickly access Eco core methods or other useful functionality. Find helper functions documentation here.

Extending Eco

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.

^ Back to Top