NAME

Nile - Visual Web App Framework Separating Code From Design Multi Lingual And Multi Theme.

SYNOPSIS

#!/usr/bin/perl

use Nile;

my $app = Nile->new();

$app->init(
	# base application path, auto detected if not set
	path	=>    dirname(File::Spec->rel2abs(__FILE__)),

	# site language for user, auto detected if not set
	lang	=>    "en-US",

	# theme used
	theme	=>    "default",
  );

#$app->run();
#exit;

my $config = $app->config;
$config->load("config.xml");
#$app->dump($config);

# connect to the database. pass the connection params or try to load it from the config object.
#$app->connect();
#$app->connect(%params);

# load langauge file general.xml
$app->lang->load("general");

# load routes file route.xml
$app->router->load("route");

# inline actions
$app->action("get", "/forum/home", sub {
	my ($self) = @_;
	# $self is set to the application context object same as $self->me in plugins
	say $self->request->virtual_host;
	say "Hello world from inline actions forum/home.";
});

$app->action("get", "/accounts/login", sub {
	my ($self) = @_;
	say "Hello world from inline actions accounts/login.";
});

$app->dispatcher->dispatch;

# run any plugin action or route
#$app->dispatcher->dispatch('/accounts/register/create');
#$app->dispatcher->dispatch('/accounts/register/create', 'POST');

# disconnect from database
#$app->disconnect();

DESCRIPTION

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

#!/usr/bin/perl

use Nile;

my $app = Nile->new();

$app->init(
	# base application path, auto detected if not set
	path	=>    dirname(File::Spec->rel2abs(__FILE__)),

	# site language for user, auto detected if not set
	lang	=>    "en-US",

	# theme used
	theme	=>    "default",
  );

#$app->run();
#exit;

my $config = $app->config;
$config->load("config.xml");
#$app->dump($config);

# connect to the database. pass the connection params or try to load it from the config object.
#$app->connect();
#$app->connect(%params);

# load langauge file general.xml
$app->lang->load("general");

# load routes file route.xml
$app->router->load("route");

# inline actions
$app->action("get", "/forum/home", sub {
	my ($self) = @_;
	# $self is set to the application context object same as $self->me in plugins
	say $self->request->virtual_host;
	say "Hello world from inline actions forum/home.";
});

$app->action("get", "/accounts/login", sub {
	my ($self) = @_;
	say "Hello world from inline actions accounts/login.";
});

$app->dispatcher->dispatch;

# run any plugin action or route
#$app->dispatcher->dispatch('/accounts/register/create');
#$app->dispatcher->dispatch('/accounts/register/create', 'POST');

# disconnect from database
#$app->disconnect();

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;

use Nile::Base;

sub home  : GET Action {
	
	my ($self) = @_;

	my $view = $self->me->view("home");
	
	$view->var(
			fname			=>	'Ahmed',
			lname			=>	'Elsheshtawy',
			email			=>	'ahmed@mewsoft.com',
			website		=>	'http://www.mewsoft.com',
			singleline		=>	'Single line variable <b>Good</b>',
			multiline		=>	'Multi line variable <b>Nice</b>',
		);

	$view->process;
	$view->render;
}

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"/>
{last_name} <vars name="lname" />
{email} <vars type="var" name='email' />
{website} <vars type="var" name="website" />

{date_now} <vars type="plugin" name="Date::Date->date" format="%Y %M %D" />
{time_now} <vars type="plugin" name="Date->now" format="%M %Y  %D" />
{date_time} <vars type="plugin" name="date" format="%M %Y  %D" />

Version: <vars type="perl"><![CDATA[print $self->me->VERSION; return;]]></vars>

<vars type="perl">system ('dir c:\\*.bat');</vars>

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

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

<!--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-->
some html content here1-5 bottom base

<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" nocase="1" defaults="year=1900|month=1|day=23" /> <post route="/blog/post/{cid:\d+}/{id:\d+}" action="Blog/Article/Post" method="post" nocase="1" /> <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.

Http Request Nile::Request.

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.

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.