the fact of real shit

Create Docker Container for Hello World with Django and uWsgi Server

I was searching a Hello World implementation for Django of Python in Docker container, but can’t find any good resource at online. So, I plan to code it myself and document it.

This is pure Docker implementation, you don’t need to create any project for Django. You just need Dockerfile to see “Hello World” at browser which powered by Django and uWsgi module.

Here is high level explanation that I’m going TODO –

  • Python, Pip and setuptools installation and upgrade
  • Create requirement.txt file
  • Execute requirement.txt file with Pip
  • Create Django project
  • Modify project settings to allow our domain in Django
  • Replace project’s urls.py to send “Hello World” string to output
  • Code to run server through uWsgi module

Entire steps I’ll do into a single Dockerfile, which we need to build and run through Docker. Here is step by step implementation of Dockerfile.

FROM python:3.11.3
WORKDIR /code
RUN pip install --upgrade pip
RUN pip install setuptools
RUN pip install -U setuptools

Its pretty straight forward, we are using Python 3.11.3 and install Pip and setuptools here.

RUN echo "Django==4.2" >> requirements.txt
RUN echo "uWSGI==2.0.25" >> requirements.txt
RUN pip install -r requirements.txt

Here we create requirement.txt file where we instruct to install Django version 4.2 and uWSGI module version 2.0.25 and then we execute the newly created requirements.txt through Pip.

RUN django-admin startproject helloworlddjango
WORKDIR /code/helloworlddjango
RUN echo "ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'helpabodessltest.shahadathossain.com']" >> helloworlddjango/settings.py

In this stage we created helloworld project with django-admin (we already Django installed) also we append our project’s settings.py to allow our domain. For this we just append “ALLOWED_HOSTS” variable value.

RUN echo "from django.urls import path" > helloworlddjango/urls.py
RUN echo "from django.shortcuts import HttpResponse" >> helloworlddjango/urls.py
RUN echo "def home_page_view_hello_world(request):" >> helloworlddjango/urls.py
RUN echo "    return HttpResponse('Hello World')" >> helloworlddjango/urls.py
RUN echo "urlpatterns = [path('', home_page_view_hello_world, name='helloworld'),]" >> helloworlddjango/urls.py

This part actually pure Python code we (re)writing our urls.py file where we actually put “Hello World” string when user visit home page of our project.

RUN adduser --disabled-password --no-create-home django
USER django
ENTRYPOINT ["uwsgi", "--http", ":9000", "--workers", "4", "--master", "--enable-threads", "--module", "helloworlddjango.wsgi"]

This is another part where we run our project through uwsgi module. We can run straightly by Django’s builtin server by “manage.py” but here I covered to run uwsgi server.

Here is link https://github.com/razonklnbd/django-hello-world-with-docker where you found complete Dockerfile

To build docker container you have to have docker in your system. After ensuring docker into system you can use following commands to build and run –

sudo docker build -t django-hello-world-mshk .
sudo docker run --name djangohelloworldmshk -d --network=host django-hello-world-mshk:latest

You need to execute into the location where you put your Dockerfile. Please feel free to change container tag and name. You may like following command of docker to see the log and to delete running container (in case you are debugging something)

sudo docker logs djangohelloworldmshk
sudo docker rm $(sudo docker stop $(sudo docker ps -a -q --filter ancestor=django-hello-world-mshk --format="{{.ID}}"))
sudo docker rmi django-hello-world-mshk

That’s all for today! Thanks.

Posted in linux, Python, webdevelopmentTagged , , , ,

JavaScript class encaptulation

My favorite JavaScript class structure –

(function(exports) {
	"use strict";
	var mySuperDupparClassOfSHKR=function(pValue){
	var myPrivateValue;
	this.setValue=function(pValue){
		myPrivateValue=pValue;
		return this;
	};
	var __construct = function(that, pValue) {
		return that.setValue(pValue);
		}(this, pValue);
	};
	exports.SuperDupparClass = {
		create : function(pValue) {
			if(typeof pValue==='undefined') throw 'please provide a value, unable to continue...';
			return new mySuperDupparClassOfSHKR(pValue);
		},
	};
})(this);

Usage as follows –

var myObj;
jQuery(document).ready(function($) {
	try{
		myObj=SuperDupparClass.create('any value');
	}catch(e){
		alert('ERR: '+e);
	}
});

 

Posted in javascript, study, webdevelopmentTagged , , ,

PHP Archive (.phar) Attaching with ZF2

PHP archive aka phar is a stream wrapper which can serve any packaged PHP library efficiently.

To create a phar document for a library (not for web output or for cli executable) is simple as pie like –

$phar = new \Phar('target-location-where-to-save.phar', 
 FilesystemIterator::CURRENT_AS_FILEINFO |
 FilesystemIterator::KEY_AS_FILENAME, 'optionalPharAliasName');
$phar->buildFromDirectory('source/lib/path');

After creating phar document, file can use to attach ZF2 standard autoloader as follows –

Zend\Loader\AutoloaderFactory::factory(array(
 'Zend\Loader\StandardAutoloader' => array(
   'autoregister_zf' => true,
   'namespaces' => array(
          'YourProjectNamespace'=>'phar:///absolute/path/of/project/phar/file.phar',
        ),
     ),
   ));

This works as simple folder of your file system. Easily distributable, packaged.

Posted in php, webdevelopmentTagged , , , , , , ,

PHP Debug efficiently with debug_backtrace

Hello today I write a small function for debug your PHP code. Its simple but powerful –

$bkTrace=function ($stack) {
 $output = '';
 
 $stackLen = count($stack);
 for ($i = 1; $i < $stackLen; $i++) {
 $entry = $stack[$i];
 
 $func = (array_key_exists('class', $entry)?$entry['class'].'\\':'').$entry['function'] . '(';
 $argsLen = count($entry['args']);
 for ($j = 0; $j < $argsLen; $j++) {
 $my_entry = $entry['args'][$j];
 if (is_string($my_entry)) {
 $func .= $my_entry;
 }
 if ($j < $argsLen - 1) $func .= ', ';
 }
 $func .= ')';
 
 $entry_file = 'NO_FILE';
 if (array_key_exists('file', $entry)) {
 $entry_file = $entry['file'];
 }
 $entry_line = 'NO_LINE';
 if (array_key_exists('line', $entry)) {
 $entry_line = $entry['line'];
 }
 $output .= $entry_file . ':' . $entry_line . ' - ' . $func . PHP_EOL;
 }
 return $output;
 };
 echo '<pre>'.$bkTrace(debug_backtrace()); exit();

 

Also for response with warning you can use above method like below –

trigger_error(‘warning @’.$bkTrace(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2)), E_USER_WARNING);

 

nJoy debugging…


			
Posted in php, webdevelopmentTagged , , 2 Comments on PHP Debug efficiently with debug_backtrace

Image size for social media (like facebook, twitter, google+, linkedin, pinterest, instagram, youtube) profile and other picture

As we faced many problem to work in social media about size of profile picture to use. Here is the dimension that analysis by renowned email marketing tools provider constant contact. Also I add some value to enrich the list –

Facebook
————————
Cover photo 815×315
Profile photo 180×180 (display area 160×160)
Fan page profile photo 200×200 (display area 176×176)
Tab 111×74
Link Image 1200×627
Image 1200×1200
Highlighted/milestone image 1200×717

Twitter
———————–
Header 1500×500
Profile photo 400×400
Image display size 880×440 (recommended)

Google+
—————————
Profile photo 250×250
Cover photo 2120×1192
Shared image 800×600

LinkedIn
————————-
Profile photo 200×200
Cover photo 646×220

Pinterest
————————–
Profile photo 600×600
Pins 600xINFINITE
Board thumbnail 222×150

Instagram
————————
Profile photo 161×161
Image viewed on desktop in lightbox as 612×612
Image feed 510×510

YouTube
—————————
Profile photo 800×800
Channel art 2560×1224
Custom video thumbnail 1280×720

* all dimensions listed in pixels

Hope it may help you to engineering the web for your client.

Posted in internet, Standard, webdevelopmentTagged , , , , , , , , , , , ,

Batch file that will create skeleton directories of ZF2

After a long time write a batch file to create a skeleton directory for Zend Framework 2 module. Hope it may help someone who work in windows 7 OS

@echo off
@setlocal ENABLEDELAYEDEXPANSION
@rem this file will create required empty directory of a ZF2 module
@rem author Shahadat Hossain Khan (shahadathossain.com)
ECHO.
IF "%~1"=="" GOTO noModuleName
SET modName=%~1
CALL :UCase %modName% _UCMN
CALL :LCase %modName% _LCMN
IF NOT EXIST "%_UCMN%" (
 MKDIR %_UCMN%
 MKDIR %_UCMN%\config
 MKDIR %_UCMN%\src
 MKDIR %_UCMN%\src\%_UCMN%
 MKDIR %_UCMN%\src\%_UCMN%\Controller
 MKDIR %_UCMN%\src\%_UCMN%\Form
 MKDIR %_UCMN%\src\%_UCMN%\Model
 MKDIR %_UCMN%\view\
 MKDIR %_UCMN%\view\%_LCMN%
 MKDIR %_UCMN%\view\%_LCMN%\%_LCMN%
 ECHO Directory created. Named - %modName%
) else (
 ECHO Directory already exist!
) 
GOTO:EOF
:noModuleName
ECHO You must provide module name along with this command as 1st argument
GOTO:EOF


:LCase
:UCase
:: Syntax: CALL :UCase _VAR1 _VAR2
:: Syntax: CALL :LCase _VAR1 _VAR2
:: _VAR1 = Variable NAME whose VALUE is to be converted to upper/lower case
:: _VAR2 = NAME of variable to hold the converted value
:: Note: Use variable NAMES in the CALL, not values (pass "by reference")
set varX=%1
set frstChar=%varX:~0,1%
set rstChar=%varX:~1%
FOR %%Z IN (Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx 
Yy Zz) DO (
 SET pX=%%Z
 set c1=!pX:~0,1!
 set c2=!pX:~1,1!
 IF /I "%0"==":UCase" (
 if %frstChar%==!c1! SET _Abet=!c1!
 if %frstChar%==!c2! SET _Abet=!c1!
 )
 IF /I "%0"==":LCase" (
 if %frstChar%==!c1! SET _Abet=!c2!
 if %frstChar%==!c2! SET _Abet=!c2!
 )
)
SET _Word_Rtrn=%_Abet%%rstChar%
SET %2=%_Word_Rtrn%
GOTO:EOF


endlocal

Usage

<your batch file name> <the module name>

Posted in php, webdevelopment, windowsTagged , , , , , , ,

Install Zend Framework 2 into Windows IIS

This article will show you how you can install Zend Framework 2 into your windows OS without composer.phar help.

1. Download latest stable copy of ZF2 from http://framework.zend.com/downloads/latest and unpack, we call it ZF2

2. Download latest stable copy of ZF2 skeleton app from https://github.com/zendframework/ZendSkeletonApplication/ and unpack, we call it ZF2Skeleton

3. Create folder like <ZF2Skeleton folder>/vendor/ZF2. Now copy ZF2/* into <ZF2Skeleton folder>/vendor/ZF2 And the final directory structure may look like following image (for ZF2 version 2.3.1 dated 20140426)

zf2 basic folder structure

4. Now point any domain into “public” folder. e.g. zf2.localhost.tld

  • 4.a. Open notepad as administrator user
  • 4.b. Add an entry to your hosts (file) like – “127.0.0.1 zf2.localhost.tld” [one host in each line]
    • 4.b.1 hosts file is typically located at C:\WINDOWS\system32\drivers\etc\hosts
  • 4.c Now save the hosts file and close
  • 4.d. Now create an entry in your IIS (6 or 7 both are same procedure) by following http://support.microsoft.com/kb/816576 with the above host name i.e. zf2.localhost.tld

5. Now you need to fix ZF2_PATH or $zf2Path variable at “/init_autoloader.php” file of root to point our “/vendor/ZF2” folder

Find following code:

$zf2Path = false;
if (getenv(‘ZF2_PATH’)) { // Support for ZF2_PATH environment variable
$zf2Path = getenv(‘ZF2_PATH’);
} elseif (get_cfg_var(‘zf2_path’)) { // Support for zf2_path directive value
$zf2Path = get_cfg_var(‘zf2_path’);
}

Replace by following code:

define(‘DS’, DIRECTORY_SEPARATOR);
define(‘APP_ROOT_PATH’, dirname(__FILE__).DS);
$zf2Path = false;
if (is_dir(APP_ROOT_PATH.’vendor’.DS.’ZF2′.DS.’library’)) {
$zf2Path = APP_ROOT_PATH.’vendor’.DS.’ZF2′.DS.’library’;
} elseif (getenv(‘ZF2_PATH’)) { // Support for ZF2_PATH environment variable or git submodule
$zf2Path = getenv(‘ZF2_PATH’);
} elseif (get_cfg_var(‘zf2_path’)) { // Support for zf2_path directive value
$zf2Path = get_cfg_var(‘zf2_path’);
}

You can now visit zf2.localhost.tld to get your expected site.

Please note, you must run latest copy of PHP (at least bigger then 5.3.23 when I write this article there I found version 5.3.28 stable for windows non thread safe version installer for download) from http://windows.php.net/download/

Now the problem is URL route in IIS. That means when you lookup into ZF2 getting started docs you may find some code to edit .htaccess of apache. What about IIS in this case?

IIS have solution of URL rewrite problem. Visit www.iis.net/urlrewrite to get the latest copy of the plugin to attach into your IIS installation. Just install this addon/plugin/extension/demon/program whatever name you called.

After installation you need a file web.config into your “<ZF2Skeleton folder>/public” folder. No matter, here we do a small trick. Just download Drupal 7+ core from https://drupal.org/project/drupal and unpack it. There you found a web.config file at root path. Just copy and paste that file into your <ZF2Skeleton folder>/public folder.

That’s all folk!

Posted in php, webdevelopment, windowsTagged , , , , , , , ,

ckeditor installation into drupal with imce

As a professional app developer, I faced to install ckeditor into drupal many times. Each times I need to dig again and again to its working. So, now I think I have to write it down that will help me and others too 😉

Install ckeditor into Drupal with IMCE

Its simple two step > Download & Put it into right place, Configure & use.

Download & Put it into right place

1. Download Drupal module of ckeditor from https://drupal.org/project/ckeditor
2. Download Drupal module for IMCE from https://drupal.org/project/imce
3. Put those module into “sites/all/modules” folder or where you think appropriate
4. Now download full version of ckeditor from http://ckeditor.com/download
5. Put full version of ckeditor into “<path where you put your ckeditor drupal module>/” please visit http://docs.cksource.com/CKEditor_for_Drupal/Open_Source/Drupal_7/Installation for details instruction where to put

That’s it, you are done the first step

Configure & use

Now enable that two module from your Drupal control panel.

1. Fix permission for ckeditor
2. Configure IMCE
3. Configure text format – Administration > Configuration > Content authoring > Text formats
3.a) For Advanced Html >> enable filter “limit allowed html tags” and leave it as it is or put “<a> <p> <div> <h1> <h2> <h3> <img> <hr> <br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <em> <b> <u> <i> <strong> <del> <ins> <sub> <sup> <quote> <blockquote> <pre>” allowed or as your requirement
3.b) For Full Html >> enable filter “limit allowed html tags” and put “<a> <abbr> <acronym> <address> <area> <article> <aside> <audio> <b> <bdo> <bgsound> <big> <blockquote> <br> <br /> <button> <canvas> <caption> <center> <cite> <code> <col> <colgroup> <command> <datalist> <dd> <del> <details> <dfn> <div> <dl> <dt> <em> <fieldset> <figcaption> <figure> <font> <footer> <form> <h1> <h2> <h3> <h4> <h5> <h6> <header> <hgroup> <hr> <hr /> <i> <img> <input> <ins> <kbd> <keygen> <label> <legend> <li> <link> <map> <mark> <marquee> <menu> <meter> <nav> <object> <ol> <optgroup> <option> <output> <p> <param> <pre> <progress> <q> <rp> <rt> <samp> <section> <select> <small> <source> <span> <strong> <sub> <summary> <sup> <table> <tbody> <td> <textarea> <tfoot> <th> <thead> <time> <tr> <tt> <ul> <var> <video> <wbr>” allowed or define tag to allow as your requirement
4. Now configure ckeditor. Specially for file browser settings. Point it to IMCE. Please configure both profile (Full, Advanced)

That’s it. nJoy….

Posted in php, webdevelopmentTagged , , , , , , ,

ABC on Internet

Introduction

The modern life is very much dependent on communicating with each other. How can we communicate with each other? Various media, like – Sending Mail through Post Office, Sending Message through Messenger, Say Hello by Land Phone or Mobile etc. At the ancient time we communicate each other with Pigeon or Messenger. But in the modern life we like to take advantages of digital technology. Internet is such a digital technology of modern life.

Elaboration of this Internet is “International Networking”. It’s a big network where computers are attached with each other all over the world. We know that, computer can attach with each other and can talk with each other, can share file with each other, can share music, can share video with each other. So, all the computer of the world is inter connecting with each other and makes a big network that virtually act as a big computer for a world. We don’t need to know how they communicate with each other. We just need to know how we can reach other computer that is outside of your computer or outside of your country. So, we can reach our friend’s computer easily to communicate with her.

Cyber café is such a place where you can use computer by paying money. Here all computers are pre-connected with internet. So, you don’t need to connect them. You need not to know how they connected, how a computer can open etc. You just need to know how you can use internet. You need to know a very basic knowledge about keyboard, mouse & monitor. Are you know, how a light is lighten by passing electricity? You just need to know where the switch to on that light is. How this switch is operated? And use this light by switch on. Internet is easy like switch on a light of your room.
Now the things you need to know for switching internet communication, is – Browser, Website, Email Address, Checking & Sending Mail, Searching or Surfing Internet for Information etc.

So, what about operating procedure of a computer? Nothing, we need not to know! Well, let me explain. When we were 2 years old, are we know about all the stuff of our room? No, not at all. But, we recognized the toy by which we can play.

About Browser & About Form

Now the most important part to use internet is browser. I like to compare browser as our “Table”. Where we can put our book for reading. It’s such a place where we can put our writing pad on it and write. So, it’s a workstation where we do our regular duties, isn’t it?

Now, what is the category of the table? Is it furniture? Yes, its furniture. In computer we can categorize “Browser” as program. If we think a computer like our room, then browser is a type of furniture like table.

Now, we already hear a word “website”. What does a website means? Website is such a place where certain information is written and can access from anywhere of the world through internet. Now, what types of information are written to the website? It’s may be the details of a product, about a place, any instruction etc. Well, let’s consider an example. Someone wants to know about “Sundarban”. Someone wants to know how he can reach to “Sundarban”. Now, if we can written all the information about “Sundarban” and put it a such open place from where anyone can access to that place and can read about “Sundarban” then she easily get all the answer about “Sundarban” from that place. That such place we call “website”. Now, what happen, if we can publish a book on “Sundarban”? Write all the information about “Sundarban” into that book. And keep that book on our table and read! Exactly, we compare our website as like as book. Where information is stored and people can read it by putting it on the table. It makes some sense about the relationship between browser and website, isn’t it?

Now, what about form? Form is nothing but a predefined question paper that need to collection information for a certain purpose. If you go to admit a school your parent need to fill up a form about you and your family. That form contains your name, your father’s name, mother’s name etc. etc. In that form we need to write but here at web form we need to type information by keyboard. After writing that form we need to submit it to school authority by handing over the filled up form. Here we need to submit it through a button that we call “Submit Button”. Its simple, we just need to know about the parts of the form. The main parts of a web form are – Text Box, Text Area, Select Box Multiple & Single, and Option Box Multiple & Single. No need to worry about form in this time. You will be familiar with web form while use net regularly.

About Mail Server & Storage Technique

As we already know that we have a common place where we preserve information for public access that is called server. We can store our information as webpage into server. Also we can store mail into that server.
Well, let’s consider a scenario. One of your friends wants to send a message through courier service. He will write a letter then go to courier service to post it. The courier service authority will send that letter to your friend’s city branch of that courier service. Then the postman will search you to give you that letter. If you don’t at home at that time the postman will drop it to your home. When you come to your home you will get that letter of your friend. Here server is act like as your home. All the mail is stored into server until you read it.

About User ID & Password

I’m trying to make you understood with some real life example. It will help the issue to understand easily. Now think you admitted into a new school and meet with your new friend. There you found that there has another friend who has the same name of you. Suppose your name “Mithila” now what other identified you? Its simple, they make a new name of you like “New Mithila” or something else. And it’s your identity at your school. In server the unique name is called “User ID”.

Now what is password? It simple, it’s a secret phrases that only known by you! Now why you need password? Basically computers don’t know you. It’s a machine. So if your friend claims that her name is “Mithila” then what happen? Cause you and your friend Mithila are using same computer. So you need a secret word or code to claim your uniqueness, isn’t it? That’s password need.

Mail Header / Parts of Mail Message

Mail header is the information about mail. You all know about traditional letter. In that letter you will find from whom you receive that letter and when you received that letter. This is called the information about letter. As like as every email have this information. We called those information as “Mail Header”.

Now what about a gift? Suppose your elder brother send a nice gift like a “Barbie Doll” to you. What you think, isn’t it nice? Your elder brother may send that gift and write a letter to you. Now what is the scenario? You getting letter with a gift. Here in electronics system we have same approach. Suppose we need to send a song with a letter. What can we do? We just need to attach that song with that email. And that is called “Attachment”. It’s also a part of email.

Now you have two another term of email header, they are – CC & BCC. CC means Carbon Copy. You all know about carbon. When we need a document more then one copy for preserving purpose or another purpose we use this carbon to copy it. In the modern technology we can photocopy that document as much as we need. So, what about CC? When you need to send your same mail to many of your friend then you need to use this option. Suppose you want to send “Eid Greetings” to your entire friends. What you will do? You will type your message and send to a friend. For another friend you need to type again and send it to that friend. May be you can copy the message text for sending the same message. But with CC option you can send the same mail to as many as you can. Just type the friends email address separated with comma and send it. It simple! Now what about BCC? You don’t need to use this BCC option now. Its elaboration is Broadcasting Carbon Copy. Its same as CC but with little functioning difference. You can use it as CC. You will learn it by using I think.

About Yahoo Profile, Yahoo Mail Account & Address Book

Yahoo profile is a profile that keeping by Yahoo. Information about you is kept by Yahoo called Yahoo Profile. In the profile it contain your name, from where you from, from where you surfing or accessing the site etc.

Yahoo Mail Account is a space where your mail stored. If someone sent you mail the mail will stored into that area until you read it. You can also store it permanently in to this account. It’s also an identification to reach you or to send you email.

Address Book is the register of email address. In this book you can save your friends email address for future use.

About Search Engine

Search engine is a special site where you can find the address of your desire word. Suppose you want to know about “123 Sisimpur”, but you don’t know where you can get information. So, first of all you need to search the address related on “123 Sisimpur” then you can go to that website to get the information about “123 Sisimpur”. From which you get the address by searching them we called it search engine. Those search engines is maintain the name of all other website. The search engine will provide the list of website that is related with your keyword. You need to put your keyword into specific text box to search. After getting the list you can easily find out your desired website.

Conclusion

Internet is easy to use & very cheap communication facilities with each other. But its global. The main fact of internet defend our real life is, if we have a permanent address we can use it to get any letter from our friend. But when we are on travel, then how can we get those letters instantly? But with email address we can get mail from anywhere anytime.

Disclaimer:

This article is written for a primary concept on internet who have no idea about internet. Basically I’m trying to establish a relationship between our real lives with internet. Internet is a vast subject. It’s not possible to give a greater knowledge at the very first time.

by-

| Md. Shahadat Hossain Khan
|
Web Developer, Square InformatiX Ltd.

Posted in internet, study, webdevelopmentTagged , , , , , , , , , , , , , , , , , , , , , ,

scope into smarty template

i’m very much fan of smarty templating. though it has many draw back but it tiny and strait froward for a small project. for smarty the varaible scope within template is very much complex. you cannot change a variable value from outside of the template.

let me explain the senario…

suppose i have a base template. named “main.tpl”

<html>
<head><title>title of the page</title></head>
<body>
<h1>your page head</h1>
{assign var="client_cur_location" value="You are now at home page."}
{include file="products.tpl" scope="global"}
<div id="pagloc">{$client_cur_location}</div>
</body>
</html>

now your products.tpl

{assign var="client_cur_location" value="<a href=\"index.php\">Home</a> &gt;&gt; Product"}
this is product listing page.

so you need to display the current location but from your included page. its not possible by smarty engin through included page. cause included page variable scope is totally local variable. here i found a solution from php mailing list. but unfortunatly it have bug when php function array_marge is changed for PHP 5

following is the complete modified, tested and working code…

/* Smarty_Compiler.class.php [near line # 950 ~ 975] */
 function _compile_include_tag($tag_args)
 {
 $attrs = $this->_parse_attrs($tag_args);

 // ADD NEXT LINE (default value of the param scope = local).
 $scope_action = "\$this->_tpl_vars = array_merge((array)\$_smarty_tpl_vars, (array)\$GLOBALS[\"_smarty_tpl_vars_temp\"]);\n";

 $arg_list = array();

 if (empty($attrs['file'])) {
 $this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__, __LINE__);
 }

 foreach ($attrs as $arg_name => $arg_value) {
 if ($arg_name == 'file') {
 $include_file = $arg_value;
 continue;
 } else if ($arg_name == 'assign') {
 $assign_var = $arg_value;
 continue;
 }
 // ADD: Startin block
 else if( $arg_name == 'scope' )
 {
 $scope = @$this->_dequote($arg_value);
 if( $scope != 'local' &&
 $scope != 'parent' &&
 $scope != 'global')
 $this->_syntax_error("invalid 'scope' attribute value");
 if( $scope == 'parent' )
 $scope_action = "";
 if( $scope == 'global' )
 {
 $scope_action = "".
 "\$array_diff = array_diff( array_keys(\$this->_tpl_vars), array_keys(\$_smarty_tpl_vars) );".
 "foreach( \$array_diff as \$key=>\$value ){".
 "\$GLOBALS[\"_smarty_tpl_vars_temp\"][\$value] = \$this->_tpl_vars[\$value];\n".
 "}";
 }
 }
 // Ending block

 if (is_bool($arg_value))
 $arg_value = $arg_value ? 'true' : 'false';
 // REPLACE THIS LINE WITH THE NEXT TWO
 // $arg_list[] = "'$arg_name' => $arg_value";
 if( $arg_name != 'scope' )
 $arg_list[] = "'$arg_name' => $arg_value";

 }

 $output = '<?php ';

 if (isset($assign_var)) {
 $output .= "ob_start();\n";
 }

 $output .=
 "\$_smarty_tpl_vars = \$this->_tpl_vars;\n";

 $_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))";
 $output .= "\$this->_smarty_include($_params);\n" .

 // REPLACE THIS LINE WITH THE NEXT ONE
 // "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" .
 $scope_action."\n".

 "unset(\$_smarty_tpl_vars);\n";
/*        original code
 "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" .
 "unset(\$_smarty_tpl_vars);\n";        */

 if (isset($assign_var)) {
 $output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n";
 }

 $output .= ' ?>';

 return $output;

 }

The value accepted for the *scope* param are: global|parent|local.
default value is *local*.

please add your valuable comment how can we improve our scope usability into our code.

please note, above php code originally is not mine. i just modified and fix the bug.

Posted in php, smarty, study, webdevelopmentTagged , , , , ,