Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/alphamarket/zinux
A simple and lightweight but powerful framework for PHP supporting MVC design pattern
https://github.com/alphamarket/zinux
Last synced: 5 days ago
JSON representation
A simple and lightweight but powerful framework for PHP supporting MVC design pattern
- Host: GitHub
- URL: https://github.com/alphamarket/zinux
- Owner: alphamarket
- License: other
- Created: 2013-05-22T14:52:57.000Z (over 11 years ago)
- Default Branch: master
- Last Pushed: 2015-09-15T01:38:12.000Z (about 9 years ago)
- Last Synced: 2024-04-24T13:45:06.769Z (7 months ago)
- Language: PHP
- Homepage: http://noise2.github.io/zinux/
- Size: 2.9 MB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
zinux
====
A simple and lightweight but powerful framework supporting MVC design pattern
--
In this project i have tried to make its uses so simple.
The zinux's policy is [Convention Over Configuration](http://en.wikipedia.org/wiki/Convention_over_configuration)
which leads it to run with minimal configuration and much more flexibility,
you will find it very convenient to use and develop.> There are also a [demo project](#demo-project) and a [zinux generator tool](#zinux-generator-tool) available.
Topics
--
* [Requirements](#requirements)
* [Installation](#installation)
* [Windows Users](#windows-users)
* [Directory Structure](#directory-structure)
* [Quick Setup](#quick-setup)
* [MVC Entities](#mvc-entities)
* [Autoloading Classes and Files](#autoloading-classes-and-files)
* [Naming Conventsion](#naming-conventsion)
* [Path Resolver](#path-resolver)
* [Bootstraping](#bootstraping)
* [General Definition of How To Boostrap](#general-definition-of-how-to-boostrap)
* [Application Bootstraps](#application-bootstraps)
* [Registering Application Bootstrap](#registering-application-bootstrap)
* [Modules Bootstrap](#modules-bootstrap)
* [Module Bootstrap Example](#module-bootstrap-example)
* [Working With MVC Entities (Basics)](#working-with-mvc-entities-basics)
* [Passing Variables To View](#passing-variables-to-view)
* [Passing Variables To Layout](#passing-variables-to-layout)
* [Changing View](#changing-view)
* [Changing Layout](#changing-layout)
* [Loading Models](#loading-models)
* [Loading Helpers](#loading-helpers)
* [A Controller Example](#a-controller-example)
* [Adavnced](#adavnced)
* [Custom Routing](#custom-routing)
* [How To Register Routers](#how-to-register-routers)
* [Binding Custom Configuration File to Application](#binding-custom-configuration-file-to-application)
* [Binding Database Handler To Application](#binding-database-handler-to-application)
* [Adding Plugins](#adding-plugins)
* [Tips](#tips)
* [Demo Project](#demo-project)
* [Zinux Generator Tool](#zinux-generator-tool)Requirements
--
* PHP version 5.5.8 or greater> If your PHP version is less than v5.5.8 but greater or equal then v5.3.10 you can use the latest version of [[email protected]](https://github.com/dariushha/zinux/tree/3.4.6) which is compatible with PHP v5.3.10. but consider that this version won't be updated with any changes may be made in zinux v4.0.0 or greater. But we strongly suggest that you upgrade your PHP version, because there are lots of new feature and some bug fixes in zinux v4.0.0 or greater.
> Note: The original zinux was written and tested in PHP v5.3.10, there is no WARRANTY for PHP's other versions
syntax/work-arounds compatibilities for this product.Installation
--
There is a [zinux installer](https://raw.github.com/dariushha/zinux/master/zinux-installer) shell script, it will
automatically download and configure your system to use zinux project freely in your system.
It also installs [zinux generator tool](https://github.com/dariushha/zg) which is an handy tool to create, manipulate
and provides solid security for your zinux project, for more information see
[Zinux Generator Tool](#zinux-generator-tool).> You will need to have [Git](http://git-scm.com/) installed before using
[zinux installer](https://raw.github.com/dariushha/zinux/master/zinux-installer).For installation just download the [zinux installer](https://raw.github.com/dariushha/zinux/master/zinux-installer)
and save it at anywhere, and run the following command `bash /path/to/your/zinux/installer` it will do the reset.Windows Users
--
For technical reasons zinux generator does not support Windows!!
You just have to clone and use the framework manually.
We are sorry about this....> Some advise for PHP developers, you cannot become a professional PHP developer and develop a full
scale PHP application within windows, you just cannot!! so maybe it is time to move your PHP developments
on linux.Directory Structure
--
Create project directory structure as follow.( or `zg new PROJECT_NAME` command in [zinux generator tool](https://github.com/dariushha/zg))
PROJECT-ROOT
|_ Modules
|_ SomeModule
|_ Controllers
|_ Models
|_ Views
|_ Layout
|_ Helper
|_ View|_ zinux (the library)
|_ public_html
|_ *
.
.
.Quick Setup
----
Considering above directory structure; in your PROJECT-ROOT/public_html/index.php file add following codes```php
Startup()
->Run()
->Shutdown();```
and also create a .htaccess in the same directory as your index.php is and add
following code route requestes to index.php.```
# PROJECT-ROOT/public_html/.htaccessRewriteEngine On
RewriteCond $1 !\.(gif|jpe?g|png|ico|js)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1
```Congratulations! you now have fully MVC magic under PROJECT-ROOT/Modules!!
> You may wondering why the folder's name passed to `\zinux\kernel\application\application`
by considering case sensitivity, does not match with `PROJECT-ROOT/Modules`!?
See [Path Resolver](#path-resolver).
> Simple, isn't it!?
MVC Entities
---
There are several entities defined in zenux framework:* Modules
* Controllers
* Actions
* Models
* Layout
* Views
* HelpersSee [naming convention](#naming-conventsion) for MVC Entities
Autoloading Classes and Files
---
zinux uses [PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/)
namespace conventions to load [MVC Entities](#mvc-entities). so as long as [MVC Entities](#mvc-entities) follow
[PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/)
the zinux's autoloader may be able to load those classes and beside `require_once '../zinux/zinux.php'`
no `require` needed for loading classes!> Note: classes and relative files should have same name. [not necessarily case-sensitive]
Naming Conventsion
---
MVC entities naming convension is as following table:
Entity
Pattern
File's Extention
Example
Modules
[module_name]Module
[FOLDER]
- DefaultModule
- UserModule
- AuthModule
Controllers
[controller_name]Controller
.php
- IndexController
- UserController
- AuthController
Actions
[model_name]Action
[Method]
- LoginAction
- FeedAction
- LogoutAction
Models
[model_name]
.php
- userModel
- Foo
- WhatEver
Layouts
[layout_name]Layout
.phtml
- DefaultLayout
- LoginLayout
- PrintLayout
Views
[view_name]View
.phtml
- IndexView
- LoginView
- AwesomeView
Helpers *
[helper_name]Helper
.php
- LanguagesHelper
- CoolHelper
- MyHelper
* Note: Helpers can either be class files or function files, see [Loading Helpers](#loading-helpers)
Path Resolver
---
In UNIX style OS(e.g Linux) which the directory mapping is case-sensitive so sometimes it gets hard when we developing
large scale projects and keeping in mind that every file and folder should named as library's defined standard naming
(i.e you cannot miss-case a letter in your namings) it sucks!!
So i have developed a very fast and effective path solver which empower the library with non-case sensitive files and folders
naming style!
> Note: The path solver class is as fast as `file_exist()` operation which is inevitable when loading items!
it uses custom made cache system which is very very fast and effective and makes path solver very smooth!
so you don't need to worry about runtime factors, when it comes to path resolver!
Bootstraping
---
General Definition of How To Boostrap
---
- Pre-strap
-
Every public method in bootstrap file which has a prefix 'pre_' gets called in pre-strap phase.
- Post-strap
-
Every public method in bootstrap file which has a prefix 'post_' gets called in post-strap phase.
Application Bootstraps
---
zinux uses bootstrap files(if any defined) to bootstrap the project, project boostraping has 2 stages:
- pre-straps
-
Before executing any operation regaurding to application, zinux launches pre-straps
methods, of course if any defined.(See [bellow](#registering-application-bootstrap) for how to definition pre-straps.)
- post-straps
-
After executing the application, zinux launches post-straps
methods, of course if any defined.(See bellow for how to definition post-straps.)
Application's bootstrap files can be located and addressed to anywhere under PROJECT-ROOT, I suggest put your application's boostrap files
in following directory path
PROJECT-ROOT
|_ application
|_ SomeAppBootstrap.php
|_ AnotherAppBoostrap.php|_ Modules
|_ zinux (the library)
|_ public_html
|_ *
.
.
.
> Note: zinux supports multiple application boostrap files.
Registering Application Bootstrap
---
Assume we have boostrap class called appBoostrap under PROJECT-ROOT/application directory as follow:
```PHP
Note: Application bootsrap classes should inherit from `\zinux\kernel\application\applicationBootstrap`.
By overwriting the index file introduced in [How To Use](#how-to-use) as follow:
```php
Startup()
/*
* This part is added to previous
* version of index.php
*/
->SetBootstrap(new \application\appBootstrap)
->Run()
->Shutdown();
```
Now your appBootstrap is registered in zinux and will get called automatically, through booting project.
> Note: In zinux you are not limited to have only one project bootstrap file, you can always
have multiple project bootstrap file: (But of course i discourage to have multiple project boostrap file, it may cause
confusion at application level.)
```PHP
$app ->Startup()
/*
* 1'st boostrap file
*/
->SetBootstrap(new \application\appBootstrap)
/*
* 2'nd boostrap file
*/
->SetBootstrap(new \application\anotherAppBootstrap)
->Run()
->Shutdown();
```
Modules Bootstrap
---
zinux uses bootstrap file(if any exists when loading modules) to bootstrap the modules,
bootstrap files are at following map:
PROJECT-ROOT
|_ Modules
|_ SomeModule
|_ Controllers
|_ Models
|_ Views
|_ SomeBootstrap.php *(your module bootstrap)|_ DefaultModule
|_ Controllers
|_ Models
|_ Views
|_ DefaultBootstrap.php *(your module bootstrap)|_ zinux (the library)
|_ public_html
|_ *
.
.
.
In bootstrap file which is a class file there are 2 kind of methods Predispatch and Postdispatch:
- Predispatch
-
Runs before dispatching to action method!
good for operations like detecting language
or checking if user is logged in or not
- Postdispatch
-
Runs after dispatching to action method!
good do some data clean up or some other things
> Note: zinux does not allow multiple boostrap file for boostraping modules.
Module Bootstrap Example
---
```PHP
";
echo "
echo "
You have requested:";
echo "
Module : ".$request->module->full_name;
echo "
Controller : ".$request->controller->full_name;
echo "
Action : ".$request->action->full_name;
echo "
View : ".$request->view->full_name;
echo "
}
# Predispatch method #2
public function PRE_echo1(\zinux\kernel\routing\request $request)
{
echo "I am predispatch #2
";
}
# Postdispatch method #1
public function POST_echo(\zinux\kernel\routing\request $request)
{
echo "I am postdispatch #1
";
}
# Postdispatch method #2
public function POST_echo1(\zinux\kernel\routing\request $request)
{
echo "I am postdispatch #2
";
}
# This function would never gets called beacause
# It does not have 'pre_' OR 'post_' naming prefix
public function FooFunc()
{
echo __METHOD__." will never get invoked...";
}
}
```
Working With MVC Entities (Basics)
==
Passing Variables To View
--
Varibales can passed to view in Controllers via following codes
```PHP
# in our controller we path varibales like this
$this->view->passed_from_controller = $some_value;
# in our view we access variable like this
echo $this->passed_from_controller;
```
Passing Variables To Layout
--
Varibales can passed to view in Controllers and Views via following codes
```PHP
# in our controller OR view we path varibales like this
$this->layout->passed_from_controller_or_view = $some_value;
# in our layout we access variable like this
echo $this->passed_from_controller_or_view;
```
Changing View
---
View can change in Controllers via following codes
```PHP
# Assume that we have Layout named 'LoginView'(case-insensitve) under current module/controller
# following code will change current view to 'LoginView'
$this->view->SetView("Login");
# disable view(i.e loading no view only view)
$this->view->SuppressView();
```
Changing Layout
---
Layout can change in Controllers and Views via following codes
```PHP
# Assume that we have Layout named 'CoolLayout'(case-insensitve) under current module
# following code will change current layout to 'CoolLayout'
$this->layout->SetLayout("COOL");
# disable any layouting(i.e loading no layout only view)
$this->layout->SuppressLayout();
```
Loading Models
---
When creating models' instances the zinux's autoloader will load models.
No need for `require` for models!
Loading Helpers
---
Helper can load at Anywhere if demanded helper is a class file just create object of that class the zinux's autoloader do the rest! but if they are function files they should load via
following code
```PHP
# Assume that we have Helper file named 'fOoModel.php'(case-insensitve) under current module
# loades fOoModel.php which is under current module ($this->request->module)
# the exact use of this code is valid in
# {Contoller}
# {Model}
# {View}
# {Layout}
new \zinux\kernel\mvc\helper("foo", $this->request->module);
# now we can use functions in 'fOoHelper.php' file
some_Function_In_fOo('Hello, world')
```
A Controller Example
--
> In this example we will have a demonstration of what we talked about above
Lets assume that we have a hypothetical controller under `SomeModule` define in
[directory structure](#directory-structure) Here is a controller example (pay attention to namespace and
relative controller path).
```PHP
request->params);
/**
* output:
*
* Array
* (
* [some] => var
* [or] => GET
* )
*
*/
}
/**
* Url map to this controller :
*
* /some/foo/feed
*/
public function FeedAction()
{
# let assume that we have some data
$data = some_data_generator();
# if the 'json' format is requested
# i.e the uri is :
# /some/foo/feed.json
if($this->request->type == "json")
{
# we dont want any view or layout here
$this->view->SuppressView();
# print out json format of data
echo json_encode($data);
return;
}
# or if the 'raw' format is requested
# i.e the uri is :
# /some/foo/feed.json
elseif($this->request->type == "raw")
{
# we dont want any view or layout here
$this->view->SuppressView();
# print out the raw format of $data
\zinux\kernel\utilities\debug::_var($data);
return;
}
# if was not a json request
# pass data to view
$this->view->some_data = $data;
# set layout to feedLayout
$this->layout->SetLayout("feed");
}
/**
* Url map to this controller :
*
* /some/foo/modeluse
*/
public function ModelUseAction()
{
/**
*
* In this action are trying to show
* how to use model and helper
*
*/
# Assume that we have a model in following path
# PROJECT-ROOT/Modules/SomeModule/Models/Xoxo.php
$o = \modules\SomeModule\Models\Xoxo();
# fetch some data from xoxo class
$this->view->new_data = $o->get_some_data();
# test data validation
if($this->view->new_data)
{
# Assume that we have a helper in following path
# PROJECT-ROOT/Modules/SomeModules/Views/Helper/A_helper.php
new \zinux\kernel\mvc\helper("a_helper", $this->request->module);
# in A_helper.php we have bellow function
$this->view->proc_data = proccess_data($this->view->new_data);
# change the view
$this->view->SetView("ValidData");
}
else
{
throw new \zinux\kernel\exceptions\notFoundException("data not found!");
}
}
}
```
> At above demo all basic operations are demonstrated.
so if you catchup with the above codes you are 100% ready to use zinux library.
Cheers!
Adavnced
==
As i mentioned before, the porpuse of zinux is convention over configuration, and the most challenging
topics in developing any applications are Project Configuration and Databse Integration.
zinux provides a very simple and flexible manner in other to bind a configuration file and database initializer.
These are optional.
Custom Routing
--
Some times in developing its good to have URL name convention, i.e for editing notes instead of linking `/note/edit/123`
you can link `/note/123/edit` this cause a naming unifying at URI level, i.e cou can also have `/note/123/delete` and ...
which is much pretty and user-friendly than `/note/edit/123` and also `/note/delete/123`.
Zinux made it very simple to have such custom routing maps, to doing so you have to have some classes
(zinux supports multiple routing class, but having multiple routing classes are discouraged for sake of clean project.)
which inherit from `\zinux\kernel\routing\routerBootstrap`, you can put your routers any where under PROJECT-ROOT
directory, i suggest put it under PROJECT-ROOT/application nearby your [application boostrap](#application-bootstraps) files,
there is an example:
```PHP
/note/edit/1234/what/so/ever?nonsences=passed
*/
$this->addRoute("/note/$1/edit$2", "/note/edit/$1$2");
}
}
```
How does it works?
In `someRoutes` class in any function called from `someRoutes::Fetch()` by adding a route `$this->addRoute()`
you can define custom made routes.
> Note: The `$1`,`$2` markers provide order in uri parts.
How To Register Routers
--
It is simple! By overwriting the index file introduced in [How To Use](#how-to-use) as follow:
```PHP
SetRouterBootstrap(new \application\someRoutes)
->Startup()
->Run()
->Shutdown();
```
Binding Custom Configuration File to Application
---
When creating `\zinux\kernel\application\application` instance in `PROJECT-ROOT/public_html/index.php` file
you can pass a instance of `\zinux\kernel\application\baseConfigLoader` to Startup().
and somewhere in your module you define a class which extents the abstract class
`\zinux\kernel\application\baseConfigLoader` which would be resposible for to load configurations for your application.
It can be a ini loader or XML loader, etc.
Usage example:
Lets suppose that we have a class named \vendor\tools\iniParser which is responsible for
loading configurations from an ini file for your project.
> Note: The zinux has its own ini parser you can use it, or define your config handler, your call.
By overwriting the index file introduced in [How To Use](#how-to-use) as follow:
```PHP
SetCacheDirectory("/path/to/cache/dir")
# setting Config iniliazer
->SetConfigIniliazer(new \zinux\kernel\utilities\iniParser("/path/to/config/file", RUNNING_ENV))
->Startup()
->Run()
->Shutdown();
```
Accessing fetched configs
Now that we have loaded our configurations we can now get access to all loaded configurations from any we in your
project via `\zinux\kernel\config\config` class!
Example:
```PHP
# Assume that in out ini file we have following lines
/*
* config.db.host = localhost
* config.db.username = USERNAME
* config.db.password = PASSWORD
* config.db.dbname = DB_NAME
*/
# output: localhost
echo \zinux\kernel\application\config::GetConfig("config", "db", "host");
# output: USERNAME
echo \zinux\kernel\application\config::GetConfig("config", "db", "username");
# output: PASSWORD
echo \zinux\kernel\application\config::GetConfig("config", "db", "password");
# output: DB_NAME
echo \zinux\kernel\application\config::GetConfig("config", "db", "dbname");
```
> Easy enough, Na!?
Binding Database Handler To Application
---
When creating `\zinux\kernel\application\application` instance in `PROJECT-ROOT/public_html/index.php` file
you can pass a instance of `\zinux\kernel\application\baseInitializer` as a secondary argument to constructor.
and somewhere in your module you define a class which extents the abstract class
`\zinux\kernel\application\baseInitializer` which would be resposible for configuring database for your application
Usage example:
Lets suppose that we have a class named \vendor\db\ActiveRecord\initializer which is responsible for initializing
[PHP ActiveRecord](#http://www.phpactiverecord.org/) for your project.
```PHP
set_model_directory('models');
$cfg->set_connections(array(
'development' => 'mysql://username:password@localhost/database_name'));
});
*
**/
}
}
```
By overwriting the index file introduced in [How To Use](#how-to-use) as follow:
```php
SetInitializer(new \vendor\db\ActiveRecord\ARInitializer())
->Startup()
->Run()
->Shutdown();
```
Your application is configured to use [PHP ActiveRecord](#http://www.phpactiverecord.org/) as database handler and
you can use PHP ActiveRecord framework freely through your project.
> Still Easy, mate!?
Adding Plugins
---
Add plugins is so simple in zinux you just add the plugin in where
ever you want under PROJECT-ROOT and start using it with out any registration or configuration!!!
What!?!?! Yup, you got it right! but make sure your have followed
[PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/) discussed in
[Autoloading Classes And Files](#autoloading-classes-and-files) in your plugins.
> Actually the zinux looks the entire project as pluging by itself!!
```PHP
/**
*
* in 'zinux/baseZinux.php' you will see the zinux
* introduces the project's root directory as a plugin
* to itself since the registerPlugin() considers plugins
* under PROJECT-ROOT directory by passing no plugin directory
* it will add the PROJECT-ROOT as a plugin!
*
*/
# require plugin file
require_once 'kernel/application/plugin.php';
# initiate a new plugin
$plugin = new kernel\application\plugin();
# treat current project as a plugin
$plugin->registerPlugin("PROJECT_ROOT");
```
> Simple, Ha!?
Note: In case of using third-party libraries you may encounter with one of two situations bellow :
Situation #1
In case of using third-party libraries which has applied its own [PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/)
you can introduce its root directory to zinux like bellow.
By overwriting the index file introduced in [How To Use](#how-to-use) as follow:
```php
registerPlugin("sundries", "Some/Where/Under/PROJECT-ROOT/sundires")
# 'FooPlug' plugin is under "Some/Where/Under/PROJECT-ROOT/FooPlug" directory
->registerPlugin("FooPlug", "Some/Where/Under/PROJECT-ROOT/FooPlug")
->Startup()
->Run()
->Shutdown();
```
> Note: If the third-party does not follow [PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/)
you have to apply the Situation #2 bellow. actually both are the same, but in Situation #1
the zinux does the autoloading for you, in Situation #2 you have to define your own autoloader
which most third-party libraries do it, you just have to call it. see bellow.
Situation #2
In case of using third-party libraries has not applied [PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/)
and also which is hard to apply [PSR-0 Standard](http://www.sitepoint.com/autoloading-and-the-psr-0-standard/)
to it, following Tip may become usefull!
> Tip: If you are using and third-party plugin, you don't need to standardize
entire plugin with PSR-0 Standard (notice that we didn't change any
PHP-ActiveRecord namespaces in [Binding Database Handler To Application](#binding-database-handler-to-application)!!)
You just create a initializer class in that plugin which define a autoloader for that pluging!
In [Binding Database Handler To Application](#binding-database-handler-to-application) example the autoloader
is defined in :
```PHP
# Where PHPActive-record lib. is stored
# location: PROJECT-ROOT/vendor/db/ActiveRecord/vendor
require_once 'vendor/ActiveRecord.php';
```
> Then you call the plugin autoloader just before making application run! i.e
by overwriting the index file introduced in [How To Use](#how-to-use) as follow:
```php
A_Func_To_Add_Plugins_Autoloader()
$app ->Startup()
->Run()
->Shutdown();
```
Tips
===
Request Types
--
The zinux supports request types i.e you can have a URI like `/news/feed.json` which points to NewsController
and FeedAction you can ouput feeds according to request type (in here `json`) in NewsController::FeedAction()! default is `html`.
Demo Project
===
You can download a demo project from [zinux-demo](https://github.com/dariushha/zinux-demo).
Zinux Generator Tool
===
[Zinux generator tool](https://github.com/dariushha/zg) is an efficient appliction designed to make use of zinux
project even easier than it is, and also makes you develop more, in a short time.
For an example, just by typing following command you will have your preoject ready:
```RUBY
# shortcut form:
# zg n new_project
zg new new_project
```
> The above command will creates a whole new project containing `defaultModule`, `appBootstrap`, `appRoutes`,
`indexConroller`, etc.
Or for an other example the following command will creates a new action and its related view in any
controller and in any desired module:
```RUBY
# shortcut form:
# zg n a action_name (controller_name) (module_name)
zg new action action_name (controller_name) (module_name)
```
For more information see Zinux Generator Project's [official page](http://dariushha.github.io/zg).
> It also provides solid code-level security for your project, by solid encryption/decryption algorithms designed to
encrypt or decrypt your project's code files.