NAME
Nile - Android Like Visual Web App Framework Separating Code From Design Multi Lingual And Multi Theme.
SYNOPSIS
#!/usr/bin/perl
use Nile;
my $app = Nile->new();
# initialize the application with the shared and safe sessions settings
$app->init(
# base application path, auto detected if not set
path => dirname(File::Spec->rel2abs(__FILE__)),
# load config files, default extension is xml
config => [ qw(config) ],
# load route files, default extension is xml
route => [ qw(route) ],
# log file name
log_file => "log.pm",
# url action name i.e. index.cgi?action=register
action_name => "action,route,cmd",
# app home page Plugin/Controller/method
default_route => "/Home/Home/home",
# force run mode if not auto detected by default. modes: "psgi", "fcgi" (direct), "cgi" (direct)
#mode => "fcgi", # psgi, cgi, fcgi
);
# set the application per single user session settings
$app->start_setting({
# site language for user, auto detected if not set
lang => "en-US",
# theme used
theme => "default",
# load language files
langs => [ qw(general) ],
# charset for encoding/decoding and output
charset => "utf-8",
});
# inline actions, return content. url: /forum/home
$app->action("get", "/forum/home", sub {
my ($self) = @_;
# $self is set to the application context object same as $self->me in plugins
my $content = "Host: " . ($self->request->virtual_host || "") ."<br>\n";
$content .= "Request method: " . ($self->request->request_method || "") . "<br>\n";
$content .= "App Mode: " . $self->mode . "<br>\n";
$content .= "Time: ". time . "<br>\n";
$content .= "Hello world from inline action /forum/home" ."<br>\n";
$content .= "أحمد الششتاوى" ."<br>\n";
$self->response->encoded(0); # encode content
return $content;
});
# inline actions, capture print statements, no returns. url: /accounts/login
$app->capture("get", "/accounts/login", sub {
my ($self) = @_;
# $self is set to the application context object same as $self->me in plugins
say "Host: " . ($self->request->virtual_host || "") . "<br>\n";
say "Request method: " . ($self->request->request_method || "") . "<br>\n";
say "App Mode: " . $self->mode . "<br>\n";
say "Time: ". time . "<br>\n";
say "Hello world from inline action with capture /accounts/login", "<br>\n";
say $self->encode("أحمد الششتاوى ") ."<br>\n";
$self->response->encoded(1); # content already encoded
});
# run the application and return the PSGI response or print to the output
# the run process will also run plugins with matched routes files loaded
$app->run();
DESCRIPTION
Nile - Android Like Visual Web App Framework Separating Code From Design Multi Lingual And Multi Theme.
Alpha version, do not use it for production. The project's homepage https://github.com/mewsoft/Nile.
The main idea in this framework is to separate all the html design and layout from programming. The framework uses html templates for the design with special xml tags for inserting the dynamic output into the templates. All the application text is separated in langauge files in xml format supporting multi lingual applications with easy translating and modifying all the text. The framework supports PSGI and also direct CGI without any modifications to your applications.
EXAMPLE APPLICATION
Download and uncompress the module file. You will find an example application folder named app.
URLs
This framework support SEO friendly url's, routing specific urls and short urls to actions.
The url routing system works in the following formats:
http://domain.com/plugin/controller/action # mapped from route file or to Plugin/Controller/action
http://domain.com/plugin/action # mapped from route file or to Plugin/Plugin/action or Plugin/Plugin/index
http://domain.com/plugin # mapped from route file or to Plugin/Plugin/plugin or Plugin/Plugin/index
http://domain.com/index.cgi?action=plugin/controller/action
http://domain.com/?action=plugin/controller/action
http://domain.com/blog/2014/11/28 # route mapped from route file and args passed as request params
The following urls formats are all the same and all are mapped to the route /Home/Home/index or /Home/Home/home (/Plugin/Controller/Action):
# direct cgi call, you can use action=home, route=home, or cmd=home
http://domain.com/index.cgi?action=home
# using .htaccess to redirect to index.cgi
http://domain.com/?action=home
# SEO url using with .htaccess. route is auto detected from url.
http://domain.com/home
APPLICATION DIRECTORY STRUCTURE
Applications built with this framework must have basic folder structure. Applications may have any additional directories.
The following is the basic application folder tree that must be created manually before runing:
├───config
├───lang
│ └───en-US
├───lib
│ └───Nile
│ └───Plugin
│ └───Home
├───log
├───route
└───theme
└───default
├───image
├───view
└───widget
CREATING YOUR FIRST PLUGIN 'HOME'
To create your first plugin called Home for your site home page, create a folder called Home in your application path /path/lib/Nile/Plugin/Home
, then create the plugin Controller file say Home.pm and put the following code:
package Nile::Plugin::Home::Home;
our $VERSION = '0.31';
use Nile::Base;
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# plugin action, return content. url is routed direct or from routes files. url: /home
sub home : GET Action {
my ($self, $me) = @_;
# $me is set to the application context object, same as $self->me inside any method
#my $me = $self->me;
my $view = $me->view("home");
$view->var(
fname => 'Ahmed',
lname => 'Elsheshtawy',
email => 'sales@mewsoft.com',
website => 'http://www.mewsoft.com',
singleline => 'Single line variable <b>Good</b>',
multiline => 'Multi line variable <b>Nice</b>',
);
#my $var = $view->block();
#say "block: " . $me->dump($view->block("first/second/third/fourth/fifth"));
#$view->block("first/second/third/fourth/fifth", "Block Modified ");
#say "block: " . $me->dump($view->block("first/second/third/fourth/fifth"));
$view->block("first", "1st Block New Content ");
$view->block("six", "6th Block New Content ");
#say "dump: " . $me->dump($view->block->{first}->{second}->{third}->{fourth}->{fifth});
return $view->out;
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# run action and capture print statements, no returns. url: /home/news
sub news: GET Capture {
my ($self, $me) = @_;
say qq{Hello world. This content is captured from print statements.
The action must be marked by 'Capture' attribute. No returns.};
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1;
YOUR FIRST VIEW 'home'
Create an html file name it as home.html, put it in the default theme folder /path/theme/default/views and put in this file the following code:
<vars type="widget" name="header" charset_name="UTF-8" lang_name="en" />
{first_name} <vars name="fname"/><br>
{last_name} <vars name="lname" /><br>
{email} <vars type="var" name='email' /><br>
{website} <vars type="var" name="website" /><br>
<br>
{date_now} <vars type="plugin" name="Date::Date->date" format="%Y %M %D %T - %a, %d %b %Y %H:%M:%S" /><br>
{time_now} <vars type="plugin" name="Date->now" format="%A %d, %B %Y %T %p" /><br>
{date_time} <vars type="plugin" name="date" format="%B %d, %Y %r" /><br>
<br>
Our Version: <vars type="perl"><![CDATA[print $self->me->VERSION; return;]]></vars><br>
<br>
<pre>
<vars type="perl">system ('dir *.cgi');</vars>
</pre>
<br>
<vars type="var" name="singleline" width="400px" height="300px" content="ahmed<b>class/subclass">
cdata start here is may have html tags and 'single' and "double" qoutes
</vars>
<br>
<vars type="var" name="multiline" width="400px" height="300px"><![CDATA[
cdata start here is may have html tags <b>hello</b> and 'single' and "double" qoutes
another cdata line
]]></vars>
<br>
<vars type="perl"><![CDATA[
say "";
say "<br>active language: " . $self->me->var->get("lang");
say "<br>active theme: " . $self->me->var->get("theme");
say "<br>app path: " . $self->me->var->get("path");
say "<br>";
]]></vars>
<br>
<br>
html content 1-5 top
<!--block:first-->
<table border="1" style="color:red;">
<tr class="lines">
<td align="left" valign="<--valign-->">
<b>bold</b><a href="http://www.mewsoft.com">mewsoft</a>
<!--hello--> <--again--><!--world-->
some html content here 1 top
<!--block:second-->
some html content here 2 top
<!--block:third-->
some html content here 3 top
<!--block:fourth-->
some html content here 4 top
<!--block:fifth-->
some html content here 5a
some html content here 5b
<!--endblock-->
<!--endblock-->
some html content here 3a
some html content here 3b
<!--endblock-->
some html content here 2 bottom
</tr>
<!--endblock-->
some html content here 1 bottom
</table>
<!--endblock-->
html content 1-5 bottom
<br><br>
html content 6-8 top
<!--block:six-->
some html content here 6 top
<!--block:seven-->
some html content here 7 top
<!--block:eight-->
some html content here 8a
some html content here 8b
<!--endblock-->
some html content here 7 bottom
<!--endblock-->
some html content here 6 bottom
<!--endblock-->
html content 6-8 bottom
<br><br>
<vars type="widget" name="footer" title="cairo" lang="ar" />
YOUR FIRST WIDGETS 'header' AND 'footer'
The framework supports widgets, widgets are small views that can be repeated in many views for easy layout and design. For example, you could make the site header template as a widget called header and the site footer template as a widget called footer and just put the required xml special tag for these widgets in all the Views you want. Widgets files are html files located in the theme 'widget' folder
Example widget header.html
<!doctype html>
<html lang="[:lang_name:]">
<head>
<meta http-equiv="content-type" content="text/html; charset=[:charset_name:]" />
<title>{page_title}</title>
<meta name="Keywords" content="{meta_keywords}" />
<meta name="Description" content="{meta_description}" />
</head>
<body>
Example widget footer.html
</body>
</html>
then all you need to include the widget in the view is to insert these tags:
<vars type="widget" name="header" charset_name="UTF-8" lang_name="en" />
<vars type="widget" name="footer" />
You can pass args to the widget like charset_name and lang_name to the widget above and will be replaced with their values.
LANGUAGES
All application text is located in text files in xml format. Each language supported should be put under a folder named with the iso name of the langauge under the folder path/lang.
Example langauge file 'general.xml':
<?xml version="1.0" encoding="UTF-8" ?>
<site_name>Site Name</site_name>
<home>Home</home>
<register>Register</register>
<contact>Contact</contact>
<about>About</about>
<copyright>Copyright</copyright>
<privacy>Privacy</privacy>
<page_title>Create New Account</page_title>
<first_name>First name:</first_name>
<middle_name>Middle name:</middle_name>
<last_name>Last name:</last_name>
<full_name>Full name:</full_name>
<email>Email:</email>
<job>Job title:</job>
<website>Website:</website>
<agree>Agree:</agree>
<company>Email:</company>
Routing
The framework supports url routing, route specific short name actions like 'register' to specific plugins like Accounts/Register/create.
Below is route.xml file example should be created under the path/route folder.
<?xml version="1.0" encoding="UTF-8" ?>
<home route="/home" action="/Home/Home/home" method="get" />
<register route="/register" action="/Accounts/Register/register" method="get" defaults="year=1900|month=1|day=23" />
<post route="/blog/post/{cid:\d+}/{id:\d+}" action="/Blog/Article/Post" method="post" />
<browse route="/blog/{id:\d+}" action="/Blog/Article/Browse" method="get" />
<view route="/blog/view/{id:\d+}" action="/Blog/Article/View" method="get" />
<edit route="/blog/edit/{id:\d+}" action="/Blog/Article/Edit" method="get" />
CONFIG
The framework supports loading and working with config files in xml formate located in the folder 'config'.
Example config file path/config/config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<admin>
<user>admin_user</user>
<password>admin_pass</password>
</admin>
<database>
<driver>mysql</driver>
<host>localhost</host>
<dsn></dsn>
<port>3306</port>
<name>blog</name>
<user>blog</user>
<pass>pass1234</pass>
<attribute>
</attribute>
<encoding>utf8</encoding>
</database>
APPLICATION INSTANCE SHARED DATA
The framework is fully Object-oriented to allow multiple separate instances, we use the shared var method on the main object to access all application shared data. The plugin modules files will have the following features.
Moose enabled Strict and Warnings enabled. a Moose attribute called 'me' or 'nile' injected in the same plugin class holds the application singleton instance to access all the shared data and methods.
you will be able to access from the plugin class the shared vars as:
$self->me->var->get("lang");
you also can use auto getter/setter
$self->me->var->lang;
URL REWRITE .htaccess
To hide the script name index.cgi from the url and allow nice SEO url routing, you need to turn on url rewrite on your web server and have .htaccess file in the application folder with the index.cgi.
Below is a sample .htaccess which redirects all requests to index.cgi file.
# Don't show directory listings for URLs which map to a directory.
Options -Indexes -MultiViews
# Follow symbolic links in this directory.
Options +FollowSymLinks
#Note that AllowOverride Options and AllowOverride FileInfo must both be in effect for these directives to have any effect,
#i.e. AllowOverride All in httpd.conf
Options +ExecCGI
AddHandler cgi-script cgi pl
# Set the default handler.
DirectoryIndex index.cgi index.html index.shtml
# save this file as UTF-8 and enable the next line for utf contents
#AddDefaultCharset UTF-8
# REQUIRED: requires mod_rewrite to be enabled in Apache.
# Please check that, if you get an "Internal Server Error".
RewriteEngine On
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# force use www with http and https so http://domain.com redirect to http://www.domain.com
#add www with https support - you have to put this in .htaccess file in the site root folder
# skip local host
RewriteCond %{HTTP_HOST} !^localhost
# skip IP addresses
RewriteCond %{HTTP_HOST} ^([a-z.]+)$ [NC]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s ^on(s)|''
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.cgi [L,QSA]
REQUEST
The http request is available as a shared object extending the CGI::Simple module. This means that all methods supported by CGI::Simple is available with the additions of these few methods:
is_ajax
is_post
is_get
is_head
is_put
is_delete
is_patch
You access the request object by $self->me->request.
ERRORS, WARNINGS, ABORTING
To abort the application at anytime with optional message and stacktrace, call the method:
$self->me->abort("application error, can not find file required");
For fatal errors with custom error message
$self->me->error("error message");
For fatal errors with custom error message and full starcktrace
$self->me->errors("error message");
For displaying warning message
$self->me->warning("warning message");
LOGS
The framework supports a log object which is a Log::Tiny object which supports unlimited log categories, so simply you can do this:
$self->me->log->info("application run start");
$self->me->log->DEBUG("application run start");
$self->me->log->ERROR("application run start");
$self->me->log->INFO("application run start");
$self->me->log->ANYTHING("application run start");
FILE
The file object provides tools for reading files, folders, and most of the functions in the modules File::Spec and File::Basename.
to get file content as single string or array of strings:
$content = $self->me->file->get($file);
@lines = $self->me->file->get($file);
supports options same as File::Slurp.
To get list of files in a specific folder:
#files($dir, $match, $relative)
@files = $self->me->file->files("c:/apache/htdocs/nile/", "*.pm, *.cgi");
#files_tree($dir, $match, $relative, $depth)
@files = $self->me->file->files_tree("c:/apache/htdocs/nile/", "*.pm, *.cgi");
#folders($dir, $match, $relative)
@folders = $self->file->folders("c:/apache/htdocs/nile/", "", 1);
#folders_tree($dir, $match, $relative, $depth)
@folders = $self->file->folders_tree("c:/apache/htdocs/nile/", "", 1);
XML
Loads xml files into hash tree using XML::TreePP
$xml = $self->me->xml->load("configs.xml");
DATABASE
The database class provides methods for connecting to the sql database and easy methods for sql operations.
bm()
$app->bm->lap("start task");
....
$app->bm->lap("end task");
say $app->bm->stop->summary;
# NAME TIME CUMULATIVE PERCENTAGE
# start task 0.123 0.123 34.462%
# end task 0.234 0.357 65.530%
# _stop_ 0.000 0.357 0.008%
say "Total time: " . $app->bm->total_time;
Benchmark specific parts of your code. This is a Benchmark::Stopwatch object.
ua()
my $response = $app->ua->get('http://example.com/');
say $response->{content} if length $response->{content};
$response = $app->ua->get($url, \%options);
$response = $app->ua->head($url);
$response = $app->ua->post_form($url, $form_data);
$response = $app->ua->post_form($url, $form_data, \%options);
Simple HTTP client. This is a HTTP::Tiny object.
Sub Modules
Views Nile::View.
Shared Vars Nile::Var.
Langauge Nile::Lang.
Request Nile::HTTP::Request.
Request Nile::HTTP::RequestPSGI.
Request Nile::HTTP::PSGI.
Response Nile::HTTP::Response.
PSGI Handler Nile::Handler::PSGI.
FCGI Handler Nile::Handler::FCGI.
CGI Handler Nile::Handler::CGI.
Dispatcher Nile::Dispatcher.
Router Nile::Router.
File Utils Nile::File.
Paginatation Nile::Paginate.
Database Nile::Database.
XML Nile::XML.
Settings Nile::Setting.
Serializer Nile::Serializer.
Deserializer Nile::Deserializer.
Serialization Nile::Serialization.
MIME Nile::MIME.
Abort Nile::Abort.
Bugs
This project is available on github at https://github.com/mewsoft/Nile.
HOMEPAGE
Please visit the project's homepage at https://metacpan.org/release/Nile.
SOURCE
Source repository is at https://github.com/mewsoft/Nile.
AUTHOR
Ahmed Amin Elsheshtawy, احمد امين الششتاوى <mewsoft@cpan.org> Website: http://www.mewsoft.com
COPYRIGHT AND LICENSE
Copyright (C) 2014-2015 by Dr. Ahmed Amin Elsheshtawy mewsoft@cpan.org, support@mewsoft.com, https://github.com/mewsoft/Nile, http://www.mewsoft.com
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.