2012年8月20日 星期一

Using FastCGI to Host PHP Applications on IIS 6.0

Introduction This article explains how to use the Microsoft IIS FastCGI extension to set up and run PHP applications on Windows XP and Windows Server® 2003 operating systems. What is FastCGI? FastCGI is a standard protocol that allows the CGI executable files for application frameworks to interface with the Web server. It differs from the standard CGI protocol in that FastCGI reuses CGI processes for multiple requests, which provides a significant performance boost as compared to CGI. Support for IIS FastCGI enables IIS to host normal CGI programs like PHP or Ruby on Rails by using the FastCGI protocol, and to offer high performance and stability for production deployment of such application frameworks. Using the IIS FastCGI support includes the following: IIS Web server IIS FastCGI extension CGI program (such as php-cgi.exe) The Web server dispatches HTTP requests to your application to the FastCGI component, which in turn launches the CGI program executable, and forwards the request for processing. Once the request is finished and the response is returned back to the server and sent to the client, the CGI process is reused for a subsequent request. This helps to avoid the high performance penalty of starting a new process for each request, which results in better performance and scalability in a production environment. To learn more about the FastCGI protocol, see http://www.fastcgi.com/devkit/doc/fcgi-spec.html. Install the FastCGI Extension for IIS 6.0 and IIS 5.1 You can download the FastCGI extension for 32-bit and 64-bit Windows XP and Windows Server 2003 here: http://www.iis.net/extensions/fastcgi When you run the FastCGI installer, it copies FastCGI-specific files to the "%windir%\system32\inetsrv" folder, and then registers and enables the FastCGI Web server extension. Of the files that the installer copies, note the following: fcgiext.dll – This is the actual FastCGI handler that communicates with FastCGI-enabled processes for processing requests. fcgiext.ini – This is the configuration file that contains the mapping of file extensions to FastCGI processes. It also contains the configuration of FastCGI process pools. fcgiconfig.js – This configures the FastCGI extension. The script updates the fcgiext.ini file, modifies the IIS metabase and recycles the Web service application pools if necessary. Download and Install PHP The FastCGI extension is fully compatible with the current official PHP 4.4.x and PHP 5.x distribution for Windows, available from http://windows.php.net/download. Since the FastCGI extension hosts and executes php processes in a single threaded manner, it is recommended that you download and install the non-thread-safe PHP build that is available for Windows. The non-thread-safe PHP build provides a performance boost from a lack of thread safety that is acceptable for a single-concurrency environment like FastCGI. Configure the FastCGI Extension to Work with PHP Once PHP is installed on Windows, you have two options to configure FastCGI: use the configuration script that is provided with the installation of the FastCGI extension, or perform all the configuration tasks manually by modifying IIS configuration settings and the fcgiext.ini file. Configure the FastCGI Extension to Work with PHP by Using the Configuration Script The configuration script with the name fcgconfig.js is provided with the installation of the FastCGI extension. It is located in %windir%\system32\inetsrv. To configure the FastCGI extension to work with PHP: Open a command prompt. Change the current directory to %windir%\system32\inetsrv. Register the PHP CGI program as the one that will be processing .php extensions by running the following configuration script: cscript fcgiconfig.js -add -section:"PHP" -extension:php -path:"C:\PHP\php-cgi.exe" Replace C:\PHP\php-cgi.exe with the path to php-cgi.exe if you installed to a directory other than C:\PHP. Note: If you do not want to register the PHP extension to be processed by the FastCGI component on your entire server, and only want to register it for a specific Web site, add a "–site:[siteId]" argument, for example: cscript fcgiconfig.js -add -section:"PHP" -extension:php -path:"C:\PHP\php-cgi.exe" –site:1 Note: For a complete list of configuration parameters that are supported by the FastCGI extension, see the FastCGI extension documentation. Manually Configure the FastCGI Extension to Work with PHP To manually configure the IIS and FastCGI extension, you must create script mappings for the PHP extension in the IIS metabase, and modify the fcgiext.ini file that is located in %windir%\system32\inetsrv. To create script mapping: Launch inetmgr.exe. Double-click the machine icon for the local computer. Right-click Web Sites and click Properties. Click the Home Directory tab. Click the Configuration… button. Click the Add… button. In the Add/Edit Application Extension Mapping dialog box, click Browse.... Navigate to the fcgiext.dll file that is located in %windir%\system32\inetsrv. Note: If you need to use FastCGI in 32-bit mode on a 64-bit machine, navigate to %windir%\SysWOW64\inetsrv. 8. In the Extension text box, enter .php. 9. Under Verbs, in the Limit to text box, enter GET,HEAD,POST. 10. Ensure that the Script engine and Verify that file exists check boxes are selected. 11. Click OK. To modify the fcigext.ini file: Once the script mapping has been added, modify the fcgiext.ini file. Add an extension to application mapping (php=PHP) to the [Types] section. Add a [PHP] section with ExePath=c:\php\php-cgi.exe (assuming you installed PHP files to the C:\PHP folder). [Types] … php=PHP … [PHP] ExePath=c:\php\php-cgi.exe 3. After you save the changes to the fcgiext.ini file, restart the application pool that is associated with the Web site that hosts your PHP applications. To configure a default document in IIS: Most PHP applications use a file named index.php as the default application document. Configure IIS to treat this file as the default content page. Launch inetmgr.exe. Double-click the machine icon for the local computer. Right-click Web Sites and click Properties. Click the Documents tab. Click the Add… button. In the Add Content Page dialog box, in the Default content page text box, enter index.php. Click OK. Set the FastCGI Configuration for Optimal Functionality, Security, and Performance with PHP IIS focuses on full PHP functionality support and performance of PHP applications that are running on the FastCGI extension. In collaboration with Zend Technologies, IIS identified the set of configuration settings for the FastCGI extension and PHP that would provide optimal functionality and performance for PHP applications when running on Windows by using the FastCGI extension. To obtain optimal functionality and performance, configure your server as follows: 1. Modify the php.ini file as follows: Set fastcgi.impersonate = 1. FastCGI under IIS supports the ability to impersonate the security tokens of the calling client. This allows IIS to define the security context under which the request runs. Set cgi.fix_pathinfo=1. cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. Previously, PHP behavior was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not define PATH_INFO. For more information about PATH_INFO, see the cgi specifications. Setting this value to 1 will cause PHP CGI to fix its paths to conform to the specification. Set cgi.force_redirect = 0. 2. Set the FastCGI configuration settings for the PHP section by running fcgiconfig.js as follows: Set the FastCGI process pool property InstanceMaxRequests to 10000. This setting specifies that the FastCGI extension will recycle php-cgi.exe after it has processed 10000 requests successfully. > cscript fcgiconfig.js -set -section:"PHP" -InstanceMaxRequests:10000 3. Configure the FastCGI extension to set the PHP_FCGI_MAX_REQUESTS environment variables for the PHP process to 10000.This setting instructs php-cgi.exe to recycle itself after it has processed 10000 requests successfully. > cscript fcgiconfig.js -set -section:"PHP" -EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000 Note: You can configure InstanceMaxRequests and PHP_FCGI_MAX_REQUESTS to use numbers other than 10000. As a general rule, ensure that the value of InstanceMaxRequests is less than or equal to the value of PHP_FCGI_MAX_REQUESTS. Test PHP CGI After installing the FastCGI extension and registering and configuring the PHP CGI, you can request your PHP application and use it normally. To test the PHP application, create and request a phpinfo.php page in your site that contains the following: You should see something like the following: Note that the Server API field indicates that PHP is hosted in FastCGI mode. reference : http://learn.iis.net/page.aspx/247/using-fastcgi-to-host-php-applications-on-iis-60/

2012年6月26日 星期二

PHP Using two class with the same name (Duplicate class name)


$v15_txt=file_get_contents($old_dir.'/libraries/joomla/version.php');
    $v15_txt=preg_replace('/class JVersion/i', 'class JVersion15', $v15_txt);
    eval('?>'.$v15_txt);
    $jvold=new JVersion15;
    $old_version = $jvold->RELEASE.'.'.$jvold->DEV_LEVEL;

    $v25_txt=file_get_contents($new_dir.'/libraries/cms/version/version.php');
    $v25_txt=preg_replace('/class JVersion/i', 'class JVersion25', $v25_txt);
    eval('?>'.$v25_txt);
    $jvnew=new JVersion25;
    $new_version = $jvnew->RELEASE.'.'.$jvnew->DEV_LEVEL;

Essential JavaScript Namespacing Patterns


In this post, I'll be discussing both intermediate and advanced patterns and approaches for namespacing in JavaScript. We're going to begin with the latter as I believe many of my readers have some prior experience in this area. If however you're new to namespacing with the language and would like to learn more about some of the fundamentals, please feel free to skip to the section titled 'namespacing fundamentals' to continue reading.

What is namespacing?

In many programming languages, namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace. They're also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified.
In JavaScript, namespacing at an enterprise level is critical as it's important to safeguard your code from breaking in the event of another script on the page using the same variable or method names as you are. With the number of third-party tags regularly injected into pages these days, this can be a common problem we all need to tackle at some point in our careers. As a well-behaved 'citizen' of the global namespace, it's also imperative that you do your best to similarly not prevent other developer's scripts executing due to the same issues.

Whilst JavaScript doesn't really have built-in support for namespaces like other languages, it does have objects and closures which can be used to achieve a similar effect.

Advanced namespacing patterns

In this section, I'll be exploring some advanced patterns and utility techniques that have helped me when working on larger projects requiring a re-think of how application namespacing is approached. I should state that I'm not advocating any of these as *the* way to do things, but rather just ways that I've found work in practice.

Automating nested namespacing

As you're probably aware, a nested namespace provides an organized hierarchy of structures in an application and an example of such a namespace could be the following:application.utilities.drawing.canvas.2d. In JavaScript the equivalent of this definition using the object literal pattern would be:
  1. var application = {  
  2.             utilities:{  
  3.                     drawing:{  
  4.                             canvas:{  
  5.                                     2d:{  
  6.                                             /*...*/  
  7.                                     }  
  8.                             }  
  9.                     }  
  10.             }  
  11. };  
Wow, that's ugly.
One of the obvious challenges with this pattern is that each additional depth you wish to create requires yet another object to be defined as a child of some parent in your top-level namespace. This can become particularly laborious when multiple depths are required as your application increases in complexity.
How can this problem be better solved? In JavaScript Patterns,Stoyan Stefanov presents a very-clever approach for automatically defining nested namespaces under an existing global variable using a convenience method that takes a single string argument for a nest, parses this and automatically populates your base namespace with the objects required.
The method he suggests using is the following, which I've updated it to be a generic function for easier re-use with multiple namespaces:
  1. // top-level namespace being assigned an object literal  
  2. var myApp = myApp || {};  
  3. // a convenience function for parsing string namespaces and  
  4. // automatically generating nested namespaces  
  5. function extend( ns, ns_string ) {  
  6.     var parts = ns_string.split('.'),  
  7.         parent = ns,  
  8.         pl, i;  
  9.     if (parts[0] == "myApp") {  
  10.         parts = parts.slice(1);  
  11.     }  
  12.     pl = parts.length;  
  13.     for (i = 0; i < pl; i++) {  
  14.         //create a property if it doesnt exist  
  15.         if (typeof parent[parts[i]] == 'undefined') {  
  16.             parent[parts[i]] = {};  
  17.         }  
  18.         parent = parent[parts[i]];  
  19.     }  
  20.     return parent;  
  21. }  
  22. // sample usage:  
  23. // extend myApp with a deeply nested namespace  
  24. var mod = extend(myApp, 'myApp.modules.module2');  
  25. // the correct object with nested depths is output  
  26. console.log(mod);  
  27. // minor test to check the instance of mod can also  
  28. // be used outside of the myApp namesapce as a clone  
  29. // that includes the extensions  
  30. console.log(mod == myApp.modules.module2); //true  
  31. // further demonstration of easier nested namespace  
  32. // assignment using extend  
  33. extend(myApp, 'moduleA.moduleB.moduleC.moduleD');  
  34. extend(myApp, 'longer.version.looks.like.this');  
  35. console.log(myApp);  
Web inspector output:
Note how where one would previously have had to explicitly declare the various nests for their namespace as objects, this can now be easily achieved using a single, cleaner line of code. This works exceedingly well when defining purely namespaces alone, but can seem a little less flexible when you want to define both functions and properties at the same time as declaring your namespaces. Regardless, it is still incredibly powerful and I regularly use a similar approach in some of my projects.

Dependency declaration pattern

In this section we're going to take a look at a minor augmentation to the nested namespacing pattern you may be used to seeing in some applications. We all know that local references to objects can decrease overall lookup times, but let's apply this to namespacing to see how it might look in practice:
  1. // common approach to accessing nested namespaces  
  2. myApp.utilities.math.fibonacci(25);  
  3. myApp.utilities.math.sin(56);  
  4. myApp.utilities.drawing.plot(98,50,60);  
  5. // with local/cached references  
  6. Var utils = myApp.utilities,  
  7. maths = utils.math,  
  8. drawing = utils.drawing;  
  9. // easier to access the namespace  
  10. maths.fibonacci(25);  
  11. maths.sin(56);  
  12. drawing.plot(98, 50,60);  
  13. // note that the above is particularly performant when  
  14. // compared to hundreds or thousands of calls to nested  
  15. // namespaces vs. a local reference to the namespace  
Working with a local variable here is almost always faster than working with a top-level global (eg.myApp). It's also both more convenient and more performant than accessing nested properties/sub-namespaces on every subsequent line and can improve readability in more complex applications.
Stoyan recommends declaring localized namespaces required by a function or module at the top of your function scope (using the single-variable pattern) and calls this a dependancy declaration pattern. One if the benefits this offers is a decrease in locating dependencies and resolving them, should you have an extendable architecture that dynamically loads modules into your namespace when required.
In my opinion this pattern works best when working at a modular level, localizing a namespace to be used by a group of methods. Localizing namespaces on a per-function level, especially where there is significant overlap between namespace dependencies would be something I would recommend avoiding where possible. Instead, define it further up and just have them all access the same reference.

Deep object extension

An alternative approach to automatic namespacing is deep object extension. Namespaces defined using object literal notation may be easily extended (or merged) with other objects (or namespaces) such that the properties and functions of both namespaces can be accessible under the same namespace post-merge.
This is something that's been made fairly easy to accomplish with modern JavaScript frameworks (eg. see jQuery's $.extend), however, if you're looking to extend object (namespaces) using vanilla JS, the following routine may be of assistance.
  1. // extend.js  
  2. // written by andrew dupont, optimized by addy osmani  
  3. function extend(destination, source) {  
  4.     var toString = Object.prototype.toString,  
  5.         objTest = toString.call({});  
  6.     for (var property in source) {  
  7.         if (source[property] && objTest == toString.call(source[property])) {  
  8.             destination[property] = destination[property] || {};  
  9.             extend(destination[property], source[property]);  
  10.         } else {  
  11.             destination[property] = source[property];  
  12.         }  
  13.     }  
  14.     return destination;  
  15. };  
  16. console.group("objExtend namespacing tests");  
  17. // define a top-level namespace for usage  
  18. var myNS = myNS || {};  
  19. // 1. extend namespace with a 'utils' object  
  20. extend(myNS, {  
  21.         utils:{  
  22.         }  
  23. });  
  24. console.log('test 1', myNS);  
  25. //myNS.utils now exists  
  26. // 2. extend with multiple depths (namespace.hello.world.wave)  
  27. extend(myNS, {  
  28.                 hello:{  
  29.                         world:{  
  30.                                 wave:{  
  31.                                     test: function(){  
  32.                                         /*...*/  
  33.                                     }  
  34.                                 }  
  35.                         }  
  36.                 }  
  37. });  
  38. // test direct assignment works as expected  
  39. myNS.hello.test1 = 'this is a test';  
  40. myNS.hello.world.test2 = 'this is another test';  
  41. console.log('test 2', myNS);  
  42. // 3. what if myNS already contains the namespace being added  
  43. // (eg. 'library')? we want to ensure no namespaces are being  
  44. // overwritten during extension  
  45. myNS.library = {  
  46.         foo:function(){}  
  47. };  
  48. extend(myNS, {  
  49.         library:{  
  50.                 bar:function(){  
  51.                     /*...*/  
  52.                 }  
  53.         }  
  54. });  
  55. // confirmed that extend is operating safely (as expected)  
  56. // myNS now also contains library.foo, library.bar  
  57. console.log('test 3', myNS);  
  58. // 4. what if we wanted easier access to a specific namespace without having  
  59. // to type the whole namespace out each time?.  
  60. var shorterAccess1 = myNS.hello.world;  
  61. shorterAccess1.test3 = "hello again";  
  62. console.log('test 4', myNS);  
  63. //success, myApp.hello.world.test3 is now 'hello again'  
  64. console.groupEnd();  
If you do happen to be using jQuery in your application, you can achieve the exact same object namespact extensibility using $.extend as seen below:
  1. // top-level namespace  
  2. var myApp = myApp || {};  
  3. // directly assign a nested namespace  
  4. myApp.library = {  
  5.     foo:function(){ /*..*/}  
  6. };  
  7. // deep extend/merge this namespace with another  
  8. // to make things interesting, let's say it's a namespace  
  9. // with the same name but with a different function  
  10. // signature: $.extend(deep, target, object1, object2)  
  11. $.extend(true, myApp, {  
  12.     library:{  
  13.         bar:function(){  
  14.             /*..*/  
  15.         }  
  16.     }  
  17. });  
  18. console.log('test', myApp);  
  19. // myApp now contains both library.foo() and library.bar() methods  
  20. // nothing has been overwritten which is what we're hoping for.  
For the sake of thoroughness, please see here for jQuery $.extend equivalents to the rest of the namespacing experiments found in this section.

Namespacing Fundamentals

Namespaces can be found in almost any serious JavaScript application. Unless you're working with a code-snippet, it's imperative that you do your best to ensure that you're implementing namespacing correctly as it's not just simple to pick-up, it'll also avoid third party code clobbering your own. The patterns we'll be examining in this section are:
  1. Single global variables
  2. Object literal notation
  3. Nested namespacing
  4. Immediately-invoked Function Expressions
  5. Namespace injection

1.Single global variables

One popular pattern for namespacing in JavaScript is opting for a single global variable as your primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:
  1. var myApplication =  (function(){  
  2.         function(){  
  3.             /*...*/  
  4.         },  
  5.         return{  
  6.             /*...*/  
  7.         }  
  8. })();  
Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as you have in the page.
One solution to this problem, as mentioned by Peter Michaux, is to use prefix namespacing. It's a simple concept at heart, but the idea is you select a unique prefix namespace you wish to use (in this example, "myApplication_") and then define any methods, variables or other objects after the prefix as follows:
  1. var myApplication_propertyA = {};  
  2. var myApplication_propertyB = {};  
  3. funcion myApplication_myMethod(){ /*..*/ }  
This is effective from the perspective of trying to lower the chances of a particular variable existing in the global scope, but remember that a uniquely named object can have the same effect. This aside, the biggest issue with the pattern is that it can result in a large number of global objects once your application starts to grow. There is also quite a heavy reliance on your prefix not being used by any other developers in the global namespace, so be careful if opting to use this.
For more on Peter's views about the single global variable pattern, read his excellent post on them here.

2. Object literal notation

Object literal notation can be thought of as an object containing a collection of key:value pairs with a colon separating each pair of keys and values. It's syntax requires a comma to be used after each key:value pair with the exception of the last item in your object, similar to a normal array.
  1. var myApplication = {  
  2.     getInfo:function(){ /**/ },  
  3.     // we can also populate our object literal to support  
  4.     // further object literal namespaces containing anything  
  5.     // really:  
  6.     models : {},  
  7.     views : {  
  8.         pages : {}  
  9.     },  
  10.     collections : {}  
  11. };  
One can also opt for adding properties directly to the namespace:
  1. myApplication.foo = function(){  
  2.     return "bar";  
  3. }  
  4. myApplication.utils = {  
  5.     toString:function(){  
  6.         /*..*/  
  7.     },  
  8.     exportfunction(){  
  9.         /*..*/  
  10.     }  
  11. }  
Object literals have the advantage of not polluting the global namespace but assist in organizing code and parameters logically. They're beneficial if you wish to create easily-readable structures that can be expanded to support deep nesting. Unlike simple global variables, object literals often also take into account tests for the existence of a variable by the same name so the chances of collision occurring are significantly reduced.
The code at the very top of the next sample demonstrates the different ways in which you can check to see if a variable (object namespace) already exists before defining it. You'll commonly see developers using Option 1, however Options 3 and 5 may be considered more thorough and Option 4 is considered a good best-practice.
  1. // This doesn't check for existence of 'myApplication' in  
  2. // the global namespace. Bad practice as you can easily  
  3. // clobber an existing variable/namespace with the same name  
  4. var myApplication = {};  
  5. /* 
  6. The following options *do* check for variable/namespace existence. 
  7. If already defined, we use that instance, otherwise we assign a new 
  8. object literal to myApplication. 
  9. Option 1: var myApplication = myApplication || {}; 
  10. Option 2  if(!MyApplication) MyApplication = {}; 
  11. Option 3: var myApplication = myApplication = myApplication || {} 
  12. Option 4: myApplication || (myApplication = {}); 
  13. Option 5: var myApplication = myApplication === undefined ? {} : myApplication; 
  14. */  
There is of course a huge amount of variance in how and where object literals are used for organizing and structuring code. For smaller applications wishing to expose a nested API for a particular self-enclosed module, you may just find yourself using this next pattern when returning an interface for other developers to use. It's a variation on the module pattern where the core structure of the pattern is an IIFE, however the returned interface is an object literal:
  1. var namespace = (function () {  
  2.     // defined within the local scope  
  3.     var privateMethod1 = function () { /* ... */ }  
  4.     var privateMethod2 = function () { /* ... */ }  
  5.     var privateProperty1 = 'foobar';  
  6.     return {  
  7.         // the object literal returned here can have as many  
  8.         // nested depths as you wish, however as mentioned,  
  9.         // this way of doing things works best for smaller,  
  10.         // limited-scope applications in my personal opinion  
  11.         publicMethod1: privateMethod1,  
  12.         //nested namespace with public properties  
  13.         properties:{  
  14.             publicProperty1: privateProperty1  
  15.         },  
  16.         //another tested namespace  
  17.         utils:{  
  18.             publicMethod2: privateMethod2  
  19.         }  
  20.         ...  
  21.     }  
  22. })();  
The benefit of object literals is that they offer us a very elegant key/value syntax to work with; one where we're able to easily encapsulate any distinct logic or functionality for our application in a way that clearly separates it from others and provides a solid foundation for extending your code.
A possible downside however is that object literals have the potential to grow into long syntactic constructs. Opting to take advantage of the nested namespace pattern (which also uses the same pattern as it's base)
This pattern has a number of other useful applications too. In addition to namespacing, it's often of benefit to decouple the default configuration for your application into a single area that can be easily modified without the need to search through your entire codebase just to alter them – object literals work great for this purpose. Here's an example of a hypothetical object literal for configuration:
  1. var myConfig = {  
  2.     language: 'english',  
  3.     defaults: {  
  4.         enableGeolocation: true,  
  5.         enableSharing: false,  
  6.         maxPhotos: 20  
  7.     },  
  8.     theme: {  
  9.         skin: 'a',  
  10.         toolbars: {  
  11.             index: 'ui-navigation-toolbar',  
  12.             pages: 'ui-custom-toolbar'  
  13.         }  
  14.     }  
  15. }  
Note that there are really only minor syntactical differences between the object literal pattern and a standard JSON data set. If for any reason you wish to use JSON for storing your configurations instead (e.g. for simpler storage when sending to the back-end), feel free to. For more on the object literal pattern, I recommend reading Rebecca Murphey's excellent article on the topic.

3. Nested namespacing

An extension of the object literal pattern is nested namespacing. It's another common pattern used that offers a lower risk of collision due to the fact that even if a namespace already exists, it's unlikely the same nested children do.
Does this look familiar?

  1. YAHOO.util.Dom.getElementsByClassName('test');  

Yahoo's YUI framework uses the nested object namespacing pattern regularly and at AOL we also use this pattern in many of our main applications. A sample implementation of nested namespacing may look like this:
  1. var myApp =  myApp || {};  
  2. // perform a similar existence check when defining nested  
  3. // children  
  4. myApp.routers = myApp.routers || {};  
  5. myApp.model = myApp.model || {};  
  6. myApp.model.special = myApp.model.special || {};  
  7. // nested namespaces can be as complex as required:  
  8. // myApp.utilities.charting.html5.plotGraph(/*..*/);  
  9. // myApp.modules.financePlanner.getSummary();  
  10. // myApp.services.social.facebook.realtimeStream.getLatest();  
You can also opt to declare new nested namespaces/properties as indexed properties as follows:
  1. myApp["routers"] = myApp["routers"] || {};  
  2. myApp["models"] = myApp["models"] || {};  
  3. myApp["controllers"] = myApp["controllers"] || {};  
Both options are readable, organized and offer a relatively safe way of namespacing your application in a similar fashion to what you may be used to in other languages. The only real caveat however is that it requires your browser's JavaScript engine first locating the myApp object and then digging down until it gets to the function you actually wish to use.
This can mean an increased amount of work to perform lookups, however developers such as Juriy Zaytsev have previously tested and found the performance differences between single object namespacing vs the 'nested' approach to be quite negligible.

4. Immediately-invoked Function Expressions (IIFE)s

An IIFE is effectively an unnamed function which is immediately invoked after it's been defined. In JavaScript, because both variables and functions explicitly defined within such a context may only be accessed inside of it, function invocation provides an easy means to achieving privacy.
This is one of the many reasons why IIFEs are a popular approach to encapsulating application logic to protect it from the global namespace. You've probably come across this pattern before under the name of a self-executing (or self-invoked) anonymous function, however I personally prefer Ben Alman's naming convection for this particular pattern as I believe it to be both more descriptive and more accurate.
The simplest version of an IIFE could be the following:
  1. // an (anonymous) immediately-invoked function expression  
  2. (function(){ /*...*/})();  
  3. // a named immediately-invoked function expression  
  4. (function foobar(){ /*..*/}());  
  5. // this is technically a self-executing function which is quite different  
  6. function foobar(){ foobar(); }  
whilst a slightly more expanded version of the first example might look like:
  1. var namespace = namespace || {};  
  2. // here a namespace object is passed as a function  
  3. // parameter, where we assign public methods and  
  4. // properties to it  
  5. (function( o ){  
  6.     o.foo = "foo";  
  7.     o.bar = function(){  
  8.         return "bar";  
  9.     };  
  10. })(namespace);  
  11. console.log(namespace);  
Whilst readable, this example could be significantly expanded on to address common development concerns such as defined levels of privacy (public/private functions and variables) as well as convenient namespace extension. Let's go through some more code:
  1. // namespace (our namespace name) and undefined are passed here  
  2. // to ensure 1. namespace can be modified locally and isn't  
  3. // overwritten outside of our function context  
  4. // 2. the value of undefined is guaranteed as being truly  
  5. // undefined. This is to avoid issues with undefined being  
  6. // mutable pre-ES5.  
  7. ;(function ( namespace, undefined ) {  
  8.     // private properties  
  9.     var foo = "foo",  
  10.         bar = "bar";  
  11.     // public methods and properties  
  12.     namespace.foobar = "foobar";  
  13.     namespace.sayHello = function () {  
  14.         speak("hello world");  
  15.     };  
  16.     // private method  
  17.     function speak(msg) {  
  18.         console.log("You said: " + msg);  
  19.     };  
  20.     // check to evaluate whether 'namespace' exists in the  
  21.     // global namespace - if not, assign window.namespace an  
  22.     // object literal  
  23. }(window.namespace = window.namespace || {});  
  24. // we can then test our properties and methods as follows  
  25. // public  
  26. console.log(namespace.foobar); // foobar  
  27. namescpace.sayHello(); // hello world  
  28. // assigning new properties  
  29. namespace.foobar2 = "foobar";  
  30. console.log(namespace.foobar2);  
Extensibility is of course key to any scalable namespacing pattern and IIFEs can be used to achieve this quite easily. In the below example, our 'namespace' is once again passed as an argument to our anonymous function and is then extended (or decorated) with further functionality:
  1. // let's extend the namespace with new functionality  
  2. (function( namespace, undefined ){  
  3.     // public method  
  4.     namespace.sayGoodbye = function(){  
  5.         console.log(namespace.foo);  
  6.         console.log(namespace.bar);  
  7.         speak('goodbye');  
  8.     }  
  9. }( window.namespace = window.namespace || {});  
namespace.sayGoodbye(); //goodbye
That's it for IIFEs for the time-being. If you would like to find out more about this pattern, I recommend reading both Ben's IIFE post and Elijah Manor's post on namespace patterns from C#.

5. Namespace injection

Namespace injection is another variation on the IIFE where we 'inject' the methods and properties for a specific namespace from within a function wrapper using this as a namespace proxy. The benefit this pattern offers is easy application of functional behaviour to multiple objects or namespaces and can come in useful when applying a set of base methods to be built on later (eg. getters and setters).
The disadvantages of this pattern are that there may be easier or more optimal approaches to achieving this goal (eg. deep object extension / merging) which I cover earlier in the article..
Below we can see an example of this pattern in action, where we use it to populate the behaviour for two namespaces: one initially defined (utils) and another which we dynamically create as a part of the functionality assignment for utils (a new namespace called tools).
  1. var myApp = myApp || {};  
  2. myApp.utils =  {};  
  3. (function() {  
  4.     var val = 5;  
  5.     this.getValue = function() {  
  6.         return val;  
  7.     };  
  8.     this.setValue = function(newVal) {  
  9.         val = newVal;  
  10.     }  
  11.     // also introduce a new sub-namespace  
  12.     this.tools = {};  
  13. }).apply(myApp.utils);  
  14. // inject new behaviour into the tools namespace  
  15. // which we defined via the utilities module  
  16. (function(){  
  17.     this.diagnose = function(){  
  18.         return 'diagnosis';  
  19.     }  
  20. }).apply(myApp.utils.tools);  
  21. // note, this same approach to extension could be applied  
  22. // to a regular IIFE, by just passing in the context as  
  23. // an argument and modifying the context rather than just  
  24. // 'this'  
  25. // testing  
  26. console.log(myApp); //the now populated namespace  
  27. console.log(myApp.utils.getValue()); // test get  
  28. myApp.utils.setValue(25); // test set  
  29. console.log(myApp.utils.getValue());  
  30. console.log(myApp.utils.tools.diagnose());  
Angus Croll has also previously suggested the idea of using the call API to provide a natural separation between contexts and arguments. This pattern can feel a lot more like a module creator, but as modules still offer an encapsulation solution, I'll briefly cover it for the sake of thoroghness:
  1. // define a namespace we can use later  
  2. var ns = ns || {}, ns2 = ns2 || {};  
  3. // the module/namespace creator  
  4. var creator = function(val){  
  5.     var val = val || 0;  
  6.     this.next = function(){  
  7.         return val++  
  8.     };  
  9.     this.reset = function(){  
  10.         val = 0;  
  11.     }  
  12. }  
  13. creator.call(ns);  
  14. // ns.next, ns.reset now exist  
  15. creator.call(ns2, 5000);  
  16. // ns2 contains the same methods  
  17. // but has an overridden value for val  
  18. // of 5000  
As mentioned, this type of pattern is useful for assigning a similar base set of functionality to multiple modules or namespaces, but I'd really only suggest using it where explicitly declaring your functionality within an object/closure for direct access doesn't make sense.

Conclusions

Reviewing the namespace patterns above, the option that I would personally use for most larger applications is nested object namespacing with the object literal pattern.
IIFEs and single global variables may work fine for applications in the small to medium range, however, larger codebases requiring both namespaces and deep sub-namespaces require a succinct solution that promotes readability and scales. I feel this pattern achieves all of these objectives well.
I would also recommend trying out some of the suggested advanced utility methods for namespace extension as they really can save you time in the long-run.


reference : http://addyosmani.com/blog/essential-js-namespacing/

wibiya widget