Skip to content

PHP – Autoloading classes with Standard PHP Library functions

In this topic, I will discuss about the power of PHPs autoloding functions and it’s capabilities to handle any situation smoothly.

GOAL:

Minimum number of include/require statements into your PHP project :)

BASICS:

When you have a long project with you, there are more chances that if you look to the starting of a file; you may find lot of include/require statements to include those different files/classes. This can be a hurdle if you have many classes defined in separate files. Thanks to PHPs autoloading functions that allows superb functionality to handle this situation. PHP has a spl_autoload_register function that can make any function an autoloading function. So if you provide spl_autoload_register(“foo::bar”) then a static function ‘bar’ of foo class would treat as an autoload function.

IMPLEMENTATION:

All you need is a class that handles the autoloading functionality. I created such class called autoloader.php which is shown below. The class has four functions namely the constructor, init, autoLoad and recursiveAutoLoad. You need to include this file in your project’s start-up environment and call the function autoload::init(), that’s all, you are all set :D . From then onwards you don’t need any include or require statements throughout your project runtime.

CODE SNIPPET:

<?php
/**
 * @author Bhargav Vadher - 2010-10-12
 *
 * An AutoLoader class for ANY level of files in
 * a project hierarchy
 *
 */

define('__ROOT', realpath ( dirname ( __FILE__)) . '/classes' ) . '/';
define('DS', DIRECTORY_SEPARATOR);
define('PS', PATH_SEPARATOR);

class Autoloader
{
      private static $__loader;

      // ----- The awesome constructor ----- //
      private function __construct ()
      {
           spl_autoload_register ( array ( $this, 'autoLoad' ) );
      }

      // ----- The fire up call for an autoloader ----- //
      public static function init ()
      {
           if ( self::$__loader == NULL )
           {
                self::$__loader = new self();
           }

           return self::$__loader;
      }

      // ----- The autoloder registered function ----- //
      public function autoLoad( $class )
      {
           $exts = array ('.php', '.class.php', '.inc');

           spl_autoload_extensions("'" . implode ( ',', $exts ) . "'");
           set_include_path(get_include_path() . PATH_SEPARATOR . __ROOT);

           foreach ($exts as $extention)
           {
                if( is_readable ( $path = __ROOT . $class . $ext) )
                {
                     require_once $path ;
                     return TRUE;
                }
           }
           self::recursiveAutoLoad( $class, __ROOT);
      }

      // ----- Recursive autoLoader, only called from autoLoder function ----- //
      private static function recursiveAutoLoad( $class, $path )
      {
           if( is_dir ( $path))
           {
                if ( ($handle = opendir ( $path)) !== FALSE )
                {
                     while (( $resource = readdir($handle) ) !== FALSE)
                     {
                          if( ($resource == '..') OR ($resource == '.'))
                          {
                               continue ;
                          }

                          if( is_dir ( $dir = $path . DS . $resource))
                          {
                               self::recursiveAutoLoad($class, $dir);
                          }
                          else if( is_readable ( $file = $path . DS . $resource))
                          {
                               require_once $file;
                          }
                     }
                     closedir( $handle);
                }
           }
      }
}

UNDERSTANDING:

When you call autoloader::init() function, first it checks whether the instance of the class is already created, if yes then it returns that instance otherwise it calls a class constructor. As you can see in the constructor that it has only one function and that is PHPs SPL (Standard PHP Library) function spl_autoload_register with argument as an array of $this and ‘autoLoad’. So it will call the same file’s autoLoad function and register it as an autoloading function for later object creation.

Alright, let’s say you included this file in an index.php file and then you fire up the function init() of autoloader. Right after that you want to create an object/instance of the class `foo` which is somewhere deep down in directories that you don’t know :) . As soon as the PHPs engine parse the new keyword, it will wake-up the autoLoad function of autoloder.php that has been registered by the init() function of the same file. Now you are at the core part. The autoLoad function is for immediate level of file/class to the path we provided as __ROOT constant. If the file is there directly inside __ROOT directory, this function will happily include that file at runtime. But what if the file is somewhere else let’s say at __ROOT/dir1/dir11/file111.php ? Well, for this we have recursiveAutoLoad function to take care and now you are at inner-core part of autoloader :P .

Basically the recursiveAutoload function includes all the files that are not at the immediate level to the __ROOT path. It start with the check of whether $path or __ROOT is a directory or not, if it is then it will create a handle for that $path and then recursively gets all the resources from that handle. The condition for the while loop is ‘until we get the resources from $handle using readdir() function’. Inside the while loop first thing we care about is skipping the current and parent directories that is ‘.’ and ‘..’ respectively. After that, it checks for whether it’s a directory or a file. If it is a directory again, no worries, call the same function again using recursion with appending the directory at the end of original path. And if it’s not a directory it must be a file, so simply include that file and keep going on. You should notice the function is_readable() that is very useful function for I/O, it basically checks whether the file path exists and it’s readable too so two shots with one arrow. Finally close the handle and you are done. This autoloder will be invoked only once throughout the runtime of any given PHP script.

USE:

Create a file called index.php and paste the following code, execute it and see what happens :)

<?php
require_once 'autoLoader.php';
Autoloader::init();
$obj = new some_class();
print_r(get_included_files());

LINKS:

Tagged ,

PHP – Singleton and Factory patterns

Every PHP developer must have heard of Design Patterns, but it all comes to benefit when actually using it efficiently. This time let me try to explain it in more on assignment type documentation :D

Goal

The goal of this post is how to (efficiently) use the PHP Design Patterns, particularly Factory pattern and Singleton pattern as of this tutorial.

Basics

Factory Pattern

As the name suggest, factory pattern is responsible for manufacturing items (objects in most cases) at run-time environment. The keyword run-time is very important here since all the resources allocation will be done at script execution time and not at compile time

Nothing is better way than example to learn coding

if( !class_exists ( $class))
{
     $splitClass = explode('_', $class);
     switch ( $count = count ( $splitClass) )
     {
          case ($count == 1) :
               require_once __PATH_TO_CLASSES . $class;
               break;
          case ($count >= 2) :
               $path = str_replace('_', '/', $class);
               require_once __PATH_TO_MODEL . $path;
               break;
          default :
               require_once __PATH_TO_CLASSES . $class;
     }
     return new $class();
}

I will explain this example in details later on while we merge both code of factory and singleton pattern…. stay tuned

Singleton Pattern

This is one of my favorite and far simplest pattern available in PHP. The basic idea is to have only one connection/link available from the same resource for multiple consumers. This pattern is being used to optimize the resource allocation and speedup the process. The very common example would be database connection because many components of our code are using database pretty frequently, it is necessary to optimize the database connection. That means no matter how many functions will call the same database connection, our code should be smart enough to return the first opened connection until we explicitly close it. Little in more detail, we don’t want database connection function to return a new connection every time someone call the connect method.

Basic idea is create a separate class for singleton method and declare a private constructor so no one outside the class can directly instantiate the class. Second most important thing is declare private static class variable that will hold the instance of the requested object/class. Furthermore, we need a method/function (usually getInstance()) that will be responsible for all the transaction for new class/object. Let’s take an example again ;)

class Singleton
{
      private static $__instances = array();     // instance holder array
      private static $__instance;                // return variable

      private function __construct()
      {
            echo '';
      }

      /**
       * Singleton implementation for any class
       *
       * @param <string> $class
       * @return <object> $__instance - return by reference
       **/
       public static function &getInstance( $class )
       {
           if ( !isset(self::$__instances[ $class ]))
           {
                require_once 'path/to/' . $class;      // include file
                self::$__instances[ $class ] = new $class ();
                self::$__instance = & self::$__instances[ $class ];
           }
           return self::$__instance;
      }

      public function __clone()
      {
           error_log ('Oo Oo .... cloning not allowed in singleton');
      }
}

As seen from the example above, whoever tries to call the function getInstance, it will first check whether the instance is already created or not. If the instance is not created  then it will create new instance of the class and store it in the holder array and if the instance is already created it will return the already created instance. Note we are using the `Return by Reference` here so it doesn’t matter wherever the class file is we create an instance of it and pass the address of the constructor of that class :) . To know more about return by reference see here.

Implementation

So now you might have got some idea about both the patterns and how they works. The fun part is still missing !!!. Remember we want maximum efficiency and code re-usability to achieve maximum performance at run-time. Let’s combine both the pattern and see how it works in real world. The example below is for general classes, i.e. singleton function for universal classes, so no matter what class you want to instantiate this example will take care of it. It combines all two code samples described earlier and some more interesting stuffs, so there we go

class Singleton
{
     private static $__instances = array();
     private static $__instance;

     /**
     * Singleton implementation for any class
     *
     * @param <string> $class
     * @return <object> $__instance - return by reference
     */

     public static function &getInstance( $class /* ,arg1, arg2 .... */)
     {
          if( array_key_exists ( $class, self::$__instances ))
          {
               self::$__instance = &self::$__instances[ $class ];
          }
          else
          {
               if( !class_exists ( $class))
               {
                    $splitClass = explode('_', $class);

                    switch ( $count = count ( $splitClass) )
                    {
                         case ($count == 1) :
                              require_once __PATH_TO_CLASSES . $class;
                              break;
                         case ($count >= 2) :
                              $path = str_replace('_', '/', $class) . '.php';
                              require_once __PATH_TO_MODEL . $path;
                              break;
                         default :
                              require_once __PATH_TO_CLASSES . $class;
                    }
               }

               $fullArguments = func_get_args();
               $shifted = array_shift($fullArguments);

               $argList = (func_num_args() - 1) > 0
                     ? implode(',', $fullArguments)
                     : NULL
               ;

               self::$__instances[ $class ] = &new $class( $argList);
               self::$__instance = &self::$__instances[ $class ];
          }

          return self::$__instance;
     }
}

This example is smart enough to take care of variable number of arguments passed to class constructor. So you can instantiate any class with variable number of arguments like

 $object = &Singleton::getInstance('ClassName', arg1, arg2, arg3 .... argn)   

The getInstance() method returns by reference so we have to call the function by reference (using & operator). Below are some examples you can do with this method

     $obj = &Singleton::getInstance('Database', $schema = 'live');
     $obj = &Singleton::getInstance('Database', $schema = 'staging');
     $obj = &Singleton::getInstance('Database', $schema = 'dev');
                              OR
     $obj = &Singleton::getInstance('Database', $host, $db, $user, $pass);
     $obj = &Singleton::getInstance('Swap', $a, $b);

Now let’s take a look at the class Singleton. The class first declared two private static class variables $__instances and $__instance. $__instances is an array that would hold different class instances as a key pair value while $__instance is static variable that would return the current requested instance. Right after, there is a check for whether the class is already initialized or not. If the class is already initialized it would be stored in a variable $__instances with class name as a key and instance as a value. If the class is not yet instantiated the function first looks whether the class exists using the function class_exists(). If not then first it will try to explode the class name to determine directory structure. So let’s say the class name is Database_Connection then it will break it into two part Database and Connection and try to look for class Connection in Database directory (Database/Connection.php). Now according to the number of arguments passed it will try to include that class file from directory structure. Here if $count is one that means we want the class with no arguments, if $count is two then we want class with 1 argument and so on.

The function will smart to get the number of arguments passed using func_get_args() and func_num_args() PHP functions and that’s why I love PHP the most :D . Once it knows the number of arguments passed, it need to remove the first argument, because it’s a class name not an actual argument. It uses array_shift() function to remove the first element from an array. Now it has all the pure arguments requested by the caller function and then it replaces all ‘_’ with the ‘\’ to create relative path i.e. the class name Database_Connection will be converted to ‘Database/Connection.php’. That’s it, then it will include it. Finally $argList contains NULL if no arguments passed and list of arguments instead. Now all we need to do is create a new element in $__instances array that points to the new requested class’s instance with class name as an index. In our case it would create new entry (‘Database_Connection => new Connection()’). Now it will store the address of this new instance into the static variable $__instance and return it to the caller :)

Facts

  • __PATH_TO_MODEL is main directory of the model folder in MVC design structure
  • __PATH_TO_CLASSES is main directory of all the classes inside the model directory. Examples would be
    • ‘/application/models/classes/setup.php’
    • ‘/application/models/classes/Database/Database_Connection.php’
    • ‘/application/models/classes/Database/Database_Functions.php’
    • ‘/application/models/classes/Database/Database_Utility.php’
    • ‘/application/models/classes/Core/Core_Setup.php’
    • ‘/application/models/classes/Core/Core_Config.php’
  • This Singleton class can be use for universal class instantiation, i.e. only one class for all instance creation.
  • This class can be useful for variable number of arguments while calling the class constructor.
  • Efficiency ++, Performance ++, Load –, Re-usability ++
  • The getInstance() function uses classes in case-sensitive manner, so Database and database will be treated as two different classes.
  • The only requirement for this class to be working is the file name should be carved according to the directory structure i.e. if you want file Connection inside Database directory it must be named Database_Connection.php to be used by the getInstance() method.
  • I hope this tutorial helps. Drop me a line if you like it.
Tagged ,

PHP – return by reference

Most of programmer knows about pass by value and pass by reference while calling functions in PHP. There is also return by value (default) and return by reference while returning value from PHP function.

Return by reference is particularly useful when you want to modify private variable of a class from outside that class ;) . Generally it’s not possible to modify private variable of the class from outside, but using return by reference that’s possible. Let’s take a look at the example


<?php
class test
{
    private $var = 5;                // private variable

    public function passByValue()    // return by value
    {
       return $this->var;
    }

    public function &passByRef()     // return by reference
    {
       return $this->var;
    }

    public function printVar()
    {
       echo $this->var . PHP_EOL;
    }
}

$obj = new test();

$old = $obj->passByValue();          // call return by value function
$old ++;                             // try increment private variable .... won't work
$obj->printVar();

$new = &$obj->passByRef();           // call return by reference function
$new ++;                             // try increment private variable ..... will work
$obj->printVar();

The class test has private variable set to 5. $old contains private variable with value 5, that was return by value, then we tried to increment it by one in hope to make it 6. Because the function passByValue returned value of $var (and not address) it didn’t increment the private variable $var.

Then $new contains private variable set to 5, that was return by function passByRef, which returned private variable by reference, and then we tried to increment it and we had the address (and not value) of private variable $var, it successfully incremented private variable from outside the class :)

Remember

  • Whenever you want a function to return by reference, that function must be declared by reference type and while calling that function we must call it by reference
  • declare by reference – public function &passByRef()
  • call by reference – $result = $obj->passByRef()

I like this kind of stuff :D

Tagged

PHP – Special operators

Along with regular operators, PHP has some special operators those are used in special cases.

These special operators are

  • error supression operator @, and
  • backtick operator `

There are some cases in coding PHP where we don’t want to output any errors even if there is an error!! At this point of time an `error supression` operator @ is useful. Consider a connection to MYSQL database and you don’t want to throw an error if the connection failed. You can achieve this functionality using @ operator as shown below.

 $conn = @mysql_connect(); 

OR

 $stringResult = @join(',', $arrResult);  

Now lets look at the backtick operator example explained below.

     $listing = `ls -l`;                  // Use of backtick operator `. Don't need to use other PHP functions here
     $listing = shell_exec ('ls -l');     // Use of shell_exec command. Gives last line of output
     $listing = exec ('pwd');             // Use of exec command. Gives whole output
     $listing = system ('pwd', $return);  // $listing contains result and $return contains return value. 0 for success

Remember:

  • The system, shell_exec and exec commands print output of CLI to the browser.
Tagged

Creating Virtual Hosts on Mac OSX

Have you ever think of having your remote website running on your own localhost ? Have you ever think that you can debug your website code locally without doing one by one remote changes?

Lets say you have a website called example.com and you want to modify some functionality in there. So what you might do is copy your remote files in which you want to do changes, download it to your localhost, make changes and upload it again to test it. Isn’t it a pain to do it all the time you want make changes? And again what if you want to add whole new functionality/module to your site?

Luckily there is a simple way to do that called Virtual Hosting. Using this method, you can host your remote content locally :) . Lets say you want to create a virtual host `example` that resembles your remote website `example.com`. There are two file on your Mac OSX that you need to modify. Lets see one by one

Before we get started copy your remote content i.e. the folder example.com inside /Library/WebServer/Documents directory on your Mac. You can copy it anywhere on your machine but by default localhost looks at  /Library/WebServer/Documents directory to get started.

Modify your hosts file

  • open hosts file – sudo vim /etc/hosts
  • you will see entries like   `127.0.0.1       localhost`
  • add your new local site name, in our case : `127.0.0.1   example`  i.e. example will be hosted on localhost
  • so now http://example resembles the functionality of your remote http://example.com

Modify your httpd-vhosts.conf file

  • open config file httpd-vhosts.conf with `sudo /etc/apache2/extra/httpd-vhosts.conf`
  • at the end of the file you need to create new virtual host that points to /Library/WebServer/Documents/example.com directory. Add the following lines at the end of this file.

<VirtualHost *:80>
     DocumentRoot "/Library/WebServer/Documents/example.com"
     ServerName example
     ErrorLog "/private/var/log/apache2/example-error_log"
<VirtualHost *:80>


On the above four lines of code, first line declares new virtual host at localhost on port 80. Second line defines the document root for the new host. Third line declares the name of newly created server, in our case its `example`. So now you can access your virtual host with http://example ;) . Last but not least, the fourth line defines error-log file for this host, in this case all the error log generated by this host will be stored in the file /private/var/log/apache2/example-error_log and you can see it with command `tail -f /var/log/apache2/example-error_log`.

That’s it, now restart your Apache by using command `sudo apachectl restart` and hit the address http://example, you should see your remote like content on your local environment. Now make as many changes you want to make, test/debug it and when you satisfy with your changes just upload whole directory (example.com) to you remote server to make it permanent remotely.

Hope this helps

Cheers ;)

Tagged , ,

Restart Apache on Mac-OSX/Linux

Here is the simplest way to restart an Apache server on Mac and Linux

For Mac Users:

sudo apachectl restart OR

sudo /usr/sbin/apachectl restart

For Linux Users:

sudo /etc/ini.d/apache2 restart

More options:

sudo apachectl graceful - same as `restart` but this will not close the current session

sudo apachectl start – to start an Apache server

sudo apachectl stop – to stop and Apache server

sudo apachectl status – to display brief status report

sudo apachectl fullstatus - to display full status report

sudo apachectl configtest – to parse the configuration file and check any syntax errors

Tagged , ,

Enable mod_rewrite in apache2 for url rewriting

I came across a silly problem. I just created a new php project named zf_demo with Zend framework.

When I ran localhost://zf_demo/public … voila it worked like a charm. Right after that i created a new controller using the command ‘zf create controller book‘ under the directory zf_demo. it created successfully and then I created three actions for book controller with ‘zf create action add book’ similarly edit and delete.

So as per plan, I should be able to access book controller with just url http://localhost/zf_demo/book but i didn’t. I search a lot about that and then finally came to know that issue was mod_rewrite rule in apache.

For any kind of URL Rewriting you must have your mod_rewrite module enabled. Now how to enable mod_rewrite in apache? In ubuntu apache is installed at /etc/apache2 by default, so you would see two directories under /etc/apache2 namely mods-enabled and mods-available. If your mod_rewrite module is enabled already then it should be inside mods-enabled directory with name rewrite.load, otherwise you just need to make a symbolic link from mods-available to mods-enables. Confused !!! never mind use the following simple command from the terminal and you should be good to go.

 sudo ln -s /etc/apache2/mods-available/rewrite.load  /etc/apache2/mods-enabled/

this will create a symbolic link of mod_rewrite to the mods-enabled. Now restart your apache2 as usually

 sudo /etc/init.d/apache2 restart or sudo apache2ctl restart 

now check for sure that mod_rewrite is enables using command

 a2enmod rewrite 

That’s it then i tried http://localhost/zf_demo/book … boom it worked like a charm. (thanks to aardvark.com)

Tagged , ,

Problems in accessing your WordPress blog from iPhone??

Sometimes you are not able to access your wordpress blog right from your smart phones particularly iPhone. It’s because of writing permission on the wordpress.

This problem occurs when you installed wordpress on your own server or hosting account but not the wordpress server itself. That means your blog url would look something like http://blog.example.com or http://example.com/blog rather than http://myblog.wordpress.com.

The solution is pretty simple. Just log in to your wordpress admin area online and find the settings tab for different settings for your blog. Next under settings you would see writing tab for all writing options. Next inside writing section there is an option like XML-RPC and than a check box in-front of it saying ‘Enable the WordPress, Movable Type, MetaWeblog and Blogger XML-RPC publishing protocols.’ Just check that option on and save it.

That’s it, now you should be able to login to your wordpress blog from your phone.

Tagged ,

Problem with AT&T Visual Voicemail on iPhone 3gs?

The Issue:

Today I came across a new kind of problem with my visual voice mail in my iPhone 3gs 3.1.2. I could able to read my voice mails by ‘pressing and holding 1 key‘, but I couldn’t able to see it in visual voice mail (service provided by iPhone).

Reason for this:

There may be two reasons that cause this kind of stupid problems. First that you have installed internet tethering application that blocks your voicemails due to the change in network profile. Second, if you have allowed google voice to handle the voice messages from your phone then you might not able to see your voice messages directly in your visual voice mail box.

Solution:

The solution for the second problem is pretty easy follow the steps and enable your visual voice mails again in it’s right place.

  • open your google voice mail account online.
  • go to settings from top right side.
  • go to first tab named ‘Phones’ and you will see your phones there. On side of every phone you will see ‘Activate/Deactive Google Voicemail on this phone‘ option
  • just activate or deactivate this option to handle voice mail by google or by your phone respectively.

Thanks Priyank!!

The solution for the first problem is little messy. Follow the steps on your iPhone

If you are experiencing the Visual Voicemail conflict caused by the upgrade to iPhone 3.1 firmware then your Visual Voicemail interface will look like the below even if you have voicemails in your voicemail inbox.

ATT iPhone 3.1 Firmware: Visual Voicemail Profile Conflict

Though I was not aware of the issue immediately my issue with Visual Voicemail started directly after upgrading my iPhone firmware to revision 3.1. It turns out that ATT started blocking the iPhone tethering hack in firmware revision 3.1 which somehow also caused an issue with Visual Voicemail. If you must have tethering work then do not update to iPhone firmware revision 3.1. If you have already upgraded to firmware 3.1 or you prefer to have latest software without Internet tethering working then use the below instructions to resolve the issue with Visual Voicemail after upgrading to iPhone firmware 3.1.

Fix Visual Voicemail Conflict With Tethering & iPhone 3.1 Firmware:

The first thing I would suggest for this solution is to remove all ‘Internet Tethering apps‘ from your iPhone, because they are on the top of list that causes this problem.

  1. Open iPhone Settings: First click on the iPhone Settings icon located on your iPhone desktop.
  2. Click General Settings: Now click on the General option from the initial Settings configuration window which will display the General settings options as shown below.

    iPhone General Settings

  3. Scroll General Settings: Scroll to the bottom of the General settings window to display the Profiles option as shown below.

    General Settings iPhone Profiles

  4. Open iPhone Profiles: Select the Profile option from the general settings that will open the iPhone Profiles configuration window as shown below.

    iPhone Profiles Configuration Window

  5. Remove BenM.at Profile: Now to remove the Visual Voicemail conflict remove the profile with BenM.at in the description field by clicking the red Remove button. Once you click the Remove button a confirmation pop up will appear as shown below. Click the second Remove button to verify you want to remove the profile.

    iPhone: Remove Profile Confirmation

  6. Test Visual Voicemail: Now call your iPhone from a different number and leave a voicemail message. Within a couple of minutes the voicemail should appear on the ATT iPhone voicemail screen as shown below.

    ATT iPhone Visual Voicemail

Hopefully ATT will eventually offer Internet Tethering as a service one day as it is a service I don’t use often though when I do it really comes in handy. I have been really disappointed with the restrictions that ATT enforces with their 3G network. They seem to claim how impressive the ATT 3G network is but data is limited even when you are paying for an unlimited data plan and they will not allow Internet tethering. If a new hack comes out for Internet tethering with iPhone 3.1 firmware or above I will definitely be installing it until ATT offers an Internet tethering service for a reasonable price even though technically it should be included in the unlimited data plan for the iPhone.

To recap the Visual Voicemail issue was a conflict with the iPhone 3.1 firmware update and the Internet tethering hack that many people have installed on their iPhones. The iPhone firmware update automatically removes the Internet tethering hack however it does not remove the profile that is also created during the hack so manually removing the profile resolves whatever the conflict was with Visual Voicemail.

Tagged , ,

Change the workspace directory for eclipse

Sometimes you don’t want the pre-configured eclipse directory that you have specified on the first run of eclipse after installation. So to change the location of workspace there is no direct option in any menu of the eclipse, all you need to do is use our old and reliable friend terminal.

Open up terminal and go to the directory where you have installed eclipse. Mine is installed at /home/bhargav/eclipse. Now follow up the commands from teminal

  • cd /path/to/eclipse
  • cd configuration/.settings
  • sudo gedit org.eclipse.ui.ide.prefs

this will open a eclipse configuration file. On this file there would be an option RECENT_WORKSPACES, all you need to do is set this option to new directory where you want to install new workspace. For example i want to create new workspace at /home/bhargav/projects/eclipse/workspace then that option would look something like

RECENT_WORKSPACES = /home/bhargav/projects/eclipse/workspace

That’s it, you have created a new workspace at specified location!!

Now if you have multiple workspace on your machine with eclipse, the question arises is how to switch to different workspaces? The answer is in the same configuration file that we just edited. There is an option like

SHOW_WORKSPACE_SELECTION_DIALOG=false

Now make this option set to true, and eclipse will ask you every time which workspace to use while you load eclipse. ;)

Tagged