<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title> &#187; php</title>
	<atom:link href="http://www.anzaan.com/category/software-development/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.anzaan.com</link>
	<description></description>
	<lastBuildDate>Sat, 26 Jun 2010 03:29:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>using java style  import to include javascript  files</title>
		<link>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/</link>
		<comments>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/#comments</comments>
		<pubDate>Sat, 23 May 2009 12:27:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[front end]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[java style package import]]></category>
		<category><![CDATA[javascript import]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=43</guid>
		<description><![CDATA[Simple way to import javascript files and package using java like conventions. Allows importing single file of all files in a package.]]></description>
			<content:encoded><![CDATA[<p>I had used a function and a little bootstrapping trick to solve my problem with including files in PHP and I was happy with it.<br />
But recently while working on a project that has a heavy javascript codebase, I started having trouble managing  all javascript file imports and all those script tags made pages look really ugly.<br />
And also I really longed for java&#8217;s clas importing capabilities in javascript such that I could import a single file based on package name or I could import a whole package.<br />
Since some of the pages I&#8217;m working requires over 15 script imports, some third-party libraries and some of our own files.<br />
And importing scripts one by one suffers from latency problems as it increases page load time and can contribute to user annoyances.<br />
So I longed for  java&#8217;s style of package and class  import and  decided to try my hand on writing some script to emulate imports based on packages.</p>
<p>I jsut used the  similar principle I used with php, but the problem is importing all files in a package isn&#8217;t possible in javascript because  javascript cannot read files form disk let alone iterate through a folder and read file content.<br />
For that there was nothing I could do except use some server-side help.</p>
<p>here&#8217;s the js file code with  function for importing js file and js files contained in a package(folder).</p>
<pre class="brush: javascript;">

//create namespace to aviod any present/ future  variable/object/funciton conflicts

if (typeof Anzaan == &quot;undefined&quot; || !Anzaan) {

Anzaan = {};
}

// array to hold all imported files so as not to import them twice
Anzaan.imports = [];

//server side URL for loading whole package content
Anzaan.packageLoaderURL='/Framework/packageLoader/';

//set the base folder for importing files
Anzaan.importBase='js/';

/**
* import a class using the java naming syntax for a class name.
*@param module the module to import
*@param  config object literal with two properties-
* config.packageLoaderURL - the server url for loading all files in a folder/package as a stream
* config.importBase - the base path for importing files
* use config only if necessary otherwise just modify Anzaan.packageLoaderURL and Anzaan.importBase
* of course you can use a different namespace or just use no namespace
*/
function Import(module, config) { //com.anzaan.framework.*

if(config){
if(config.packageLoaderURL)
Anzaan.packageLoaderURL=config.packageLoaderURL;

if(config.importBase)
Anzaan.importBase=config.importBase;
}

// if this import has already happened, don't bother,
if (Anzaan.imports[module] )
return ;

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';

var src='';
var folders=module.split(&quot;.&quot;);
for(var i=0;i&lt;folders.length;i++){

if(folders[i].indexOf('*') &lt; 0)
src+=folders[i]+&quot;/&quot;;
}
src=src.substring(0,src.length-1);//remove the last slash

if (module.indexOf('*') &lt; 0) { //if not package import
src=Anzaan.importBase+src+&quot;.js&quot;;
script.src=src;

} else {
script.src=Anzaan.packageLoaderURL+&quot;?package=&quot;+Anzaan.importBase+src;
}

head.appendChild(script);
Anzaan.imports[module] = module;
}
</pre>
<p>The config parameter is optional. It shouldn&#8217;t really be used unless you want to load files from locations other tahn the default location of your application and want to use other URL for loading script files.</p>
<p>Just modify the global variables Anzaan.packageLoaderURL and Anzaan.importBase to set the base path and the serverside URL for loading scripts in folder.<br />
And of course rename Anzaan to something more meaningful for you.</p>
<p>Now on the server side here&#8217;s a simple php script that services the script file requests.<br />
It loads contents from js flies that reside in folder specified by &#8216;package&#8217;  variable.</p>
<p>packageLoader.php<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<pre class="brush: php;">
&lt;?php

$folder=$_GET[&quot;package&quot;]; // get the package name

$dir = opendir($folder); //open directory

while (($file = readdir($dir)) !== false) {
if (strrpos($file, '.js')) {

echo file_get_contents($folder.'/'.$file); //printout the content of file

}
}

?&gt;
</pre>
<p>and here&#8217;s a Java Servlet for doing the same thing:</p>
<pre>JSPackageLoaderServlet.java</pre>
<pre class="brush: java;">

public class JSPackageLoaderServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType(&quot;text/plain&quot;);
ServletOutputStream out = response.getOutputStream();

String packagePath = request.getParameter(&quot;package&quot;);

StringBuilder sb = new StringBuilder();

File myDir = new File(getServletContext().getRealPath(packagePath));
if (myDir.exists() &amp;&amp; myDir.isDirectory()) {
File[] files = myDir.listFiles();
for (int y = 0; y &lt; files.length; y++) {

String line = &quot;&quot;;
BufferedReader in = new BufferedReader(new FileReader(files[y]));

while ((line = in.readLine()) != null) {
sb.append(line);

}

}

}
out.print(sb.toString());
}
}
</pre>
<p>Here&#8217;s the usage:</p>
<pre class="brush: javascript;">
Import('anzaan.event.EvenHandler');
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>using java style import to include files  in php</title>
		<link>http://www.anzaan.com/2009/05/using-java-style-import-to-include-files-in-php/</link>
		<comments>http://www.anzaan.com/2009/05/using-java-style-import-to-include-files-in-php/#comments</comments>
		<pubDate>Sat, 23 May 2009 08:56:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=38</guid>
		<description><![CDATA[ ]]></description>
			<content:encoded><![CDATA[<p>I really like the way java handles packages and the way it import classes based on package description.<br />
Last year while  developing  a php  based CMS application, I faced shitload of trouble when it came to file including.<br />
The problem was if I was making a normal page request, realtive URL&#8217;s  worked this way:<br />
&#8220;../framework/service/DataService.php&#8221; and I used</p>
<pre class="brush: php;">
inlcude_once(&quot;../framework/service/DataService.php&quot;)
</pre>
<p>to include a script.</p>
<p>But for accessing files using AJAX request for some weird reason I had to use single dot at the start of the path &#8211; instead :</p>
<pre class="brush: php;">
inlcude_once(&quot;./framework/service/DataService.php&quot;).
&lt;pre&gt;</pre>
<p>And as such I hit a kind of brick-wall because say I have a script that I need to accesss normally and via AJAX call, and the file included some other files, then what do i do?  I either have to put duplicate includes one with single dot and one with double dots at the begining and there was no way I was going to do such stupid things.<br />
So I set out to solve this truely annoying problem.<br />
I found some scripts in the net that did what I needed, almost&#8230;.<br />
I stole a script from the net and modified to suit my need. And since then my life has been so easy  you won&#8217;t believe.<br />
with that scrip all I had to do was import files just the way I do in good old Java.<br />
Even better I started using the same conventions as java.</p>
<p>So my imports look like this nowaday:</p>
<pre class="brush: php;">
import(&quot;com.barahisolutions.cms.model.MenuPermission&quot;);
</pre>
<p>and if I want to import all files in a package I use the same comvention as java and<br />
and use &#8216;*&#8217; instead of file name.</p>
<pre class="brush: php;">
import(&quot;com.barahisolutions.cms.model.*&quot;);
</pre>
<p>The code looks very neat and all my scripts are neatly organised in packages and life has been good ever since.</p>
<p>I divide all my scripts into two main folders. One <strong>classses </strong>to hold all project specific classes and one <strong>lib</strong> to hold all my library files. and i set these folders as include path using <strong>ini_set</strong>. I just have to do one <strong>inculde_once</strong> statement to include the file that has the <strong>import </strong>function and for the rest I use <strong>import </strong>function to include the required classes and files.</p>
<p>Of course its not all that simple. Because relative path to the <strong>classes </strong>and <strong>lib </strong>folders may be different depending on where the page/script that uses the <strong>import </strong>function is located. so instead of using <strong>ini_set</strong> in every place I want to use the <strong>import </strong>function, I used a little trick to solve the problem. I created one more function bootstrap and used it to calculate the relative path to the <strong>classes </strong>and <strong>lib </strong>folder before doing the ini<strong>_</strong>set.<br />
From there all I have to do is include this file as a bootstrap for my applicaitons and I was ready use the <strong>import</strong> function for all my file include needs.</p>
<p>Here&#8217;s a stripped down version of the bootstrap file with the required funcitons.</p>
<p>bootstrap.php.</p>
<pre class="brush: php;">
// array to keep track of all the already included files
$_imports = array();

// set the include path to the classes and lib folder
function bootstrap(){

//get the current script's path  relative to the applicaiton root folder
$rel_paths=explode('/',$_SERVER['SCRIPT_NAME']);
$path=&quot;&quot;;

// calculate the depth relative to the root folder
if(sizeof($rel_paths)&gt;2){
for($i=2; $i&lt; (sizeof($rel_paths)-1); $i++){
$path.=&quot;../&quot;;
}
}
// set the include path for our application's library and class files
ini_set('include_path', $path.'lib' . (DIRECTORY_SEPARATOR == '/' ? ':' : ';') .
$path.'classes'.(DIRECTORY_SEPARATOR == '/' ? ':' : ';') );

}
//just execute the funciton.
bootstrap();

/**
* Import a class using the java naming syntax for a class name.
* use * to include all files in a package
* @param string $name The name of the package to be imported
* @return void
*/

function import($import) {

// if this import has already happened, don't bother,
if (isset($_imports[$import]) )
return true;

// seperate import into a package and a class
$lastDot = strrpos($import, '.');
$class = $lastDot ? substr($import, $lastDot + 1) : $import;
$package = substr($_import, 0, $lastDot);

// create a folder path out of the package name
$folder = '' . ($package ? str_replace('.', '/', $package) : '');
$file = &quot;$folder/$class.php&quot;;

if ($class != '*') {
// add the class and it's file location to the imports array

include_once($file);

} else {
// add all the classes from this package and their file location to the imports array
// first log the fact that this whole package was alread imported
$_imports[&quot;$package.*&quot;] = 1;
$dir = opendir($folder);
while (($file = readdir($dir)) !== false) {
if (strrpos($file, '.php')) {
include_once(&quot;$folder/$file&quot;);
}
}
}

$_imports[$import] = $import;
}
</pre>
<p>That&#8217;s all that is required.</p>
<p>Now if you include this file, you  can simple use the import statement to import files that you need in your script.</p>
<p>samle usage: (its assumed that the file that actually uses MenuController class has already included the bootstrap.php file.<br />
class MenuController.php</p>
<pre class="brush: php;">
//import all the required classes
import('com.barahisolutions.cms.model.Menu');
import('com.barahisolutions.cms.dao.MenuDAO');
import('com.barahisolutions.cms.dao.UserPermissionDAO');
import('com.barahisolutions.framework.menu.VerticalMenu');

class MenuController {

// your business logic here

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/using-java-style-import-to-include-files-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
