Pages

Sunday, September 15, 2013

PHP-Loop Queston's

1. for($i=1;$i++;$i<100)
echo $i;

2. for($i=0;$i++;$i<100)
echo $i;

How many times will the loop execute in both the cases.

Answers:

1. Infinite why?
We know that for loop has 3 blocks 1st is assignment 2nd is condition and 3rd is increment.

Now in first block we have assignment $i=1 We are fine with it
In second block we are having $i++ which means that it will check for value of $i as condition before incrementing so $i=1 and increment $i to 2 and again in next pass we have $i=2 which is again true value>0 results in true.
and it will go on until falls short of memory.

2. 0 Why?

$i=0 initially checked that condition before increment $i=0 which returns false and as such loop halts.


OOPS-PHP-Magic Methods

1. __get($property)

Get value for a property set in a class foe example

 function __get($property)  
 {  
 return $this->properties[$property];  
 }  


Usage: echo $st->name;

2. __set($property,$value) Set value for a property
 function __set($property, $value)  
 {  
 $this->properties[$property]="AutoSet {$property} as: ".$value;  
 }  


Usage: $st->roll=16;

3. __call()
overloads any undefined function in a class.Thus we can also call an undefined function and show custom error message.

 function __call($method, $arguments)  
 {  
 echo "You called a method named {$method} with the following  
 arguments <br/>";  
 print_r($arguments);  
 echo "<br/>";  
 }  

Usage: $ol->notAnyMethod("boo");

OOPS-Static keyword,Singleton Design Pattern and its implementation

Static keyword is useful in creating Singleton design pattern because in such a scenario changes made by 1 object to a variable is reflected in all the objects of that class in that request.

Here is my example code with Singleton Design Pattern.

What I was trying to do is I was trying a singleton object over different request's and was trying to see whether it maintains its state or not. And it doesn't I tried running this page from different browser's and I failed to retrieve data of previous request's or session's.

Singleton Pattern is just needed so that only one object access at a time a resource to avoid conflict's

Singleton's are used to write log's and database access,maintain configuration variable's.

And that is when I realized the importance of an Application Server over a Web Server where we can create application object's.

 <?php  
 session_start();  
 //Singleton class example  
 error_reporting(E_ALL);  
 final class UserInfo  
 {  
   static $user=null;  
   static $instance=NULL;  
   public static function Instance()  
   {  
     if (self::$instance === null) {  
       self::$instance = new UserInfo();  
     }  
     return self::$instance;  
   }  
   /*  
    * Shows the array  
    */  
   public static function showUser()  
   {  
     if(self::$user!=null)  
     {  
       foreach(self::$user as $key=>$value)  
       {  
         echo "<br/>Sessionid ".$key." is assigned to ".$value."<br/>";  
       }  
     }  
   }  
   /*  
    * Adds session Id and user to the array  
    */  
   public static function AddUser()  
   {  
     echo "<br/>";  
     echo "Object count is ==>";  
     echo $ucount=count(self::$user);  
     echo "<br/>";  
     if(self::$user===null)  
     {  
       self::$user=array();  
       self::$user[session_id()]="User ".($ucount+1);  
       //print_r(self::$user);  
     }  
     else   
     {  
       if(!(array_key_exists(session_id(),self::$user)))  
       {  
         self::$user[session_id()]="User ".$ucount+1;  
       }  
     }  
   }  
   private function __construct()  
   {  
   }  
 }  
 echo "My Session Id is :". session_id();  
 UserInfo::Instance()->AddUser();  
 $fact1= UserInfo::Instance();  
 $fact= UserInfo::Instance();  
 $fact1->AddUser();  
 $fact->showUser();  
 UserInfo::Instance()->showUser();  
 if($fact1===$fact)  
   echo "Matches";  
 /*  
  * ERROR LINE  
  */  
 //$fact3= new UserInfo();  
 ?>  

Output is:
 My Session Id is :p15snn5ebgn52ftsj0eb43e4n0  
 Object count is ==>0  
 Object count is ==>1  
 Sessionid p15snn5ebgn52ftsj0eb43e4n0 is assigned to User 1  
 Sessionid p15snn5ebgn52ftsj0eb43e4n0 is assigned to User 1  
 Matches  

As you can see above is mine singleton class with a private constructor.I have 2 static methods one to store data and other to show data

In first case I have added user name as value and corresponding session id as key to the array.
I have called my method in 2 way's directly via class and by an object.

In the second call count goes 1

Finally I call show user in 2 way's and the 2 object's matches as per the condition

OOPS-What is the difference between Static and Final Keyword

Static
A static method remains common for all objects and can be called directly without the need of creation of any object.

For Example : classname::functionname();

A static property on the other end remains common for all the objects.It preserves its last changed state by any object.

Final
Final keyword on other end does not allows a class to be extended a method to be overridden in subclass or to change a property respective to its use in a class.

Saturday, September 14, 2013

OOPS-PHP4,PHP5-difference

1. In PHP4 there are no access modifiers everything is open we can't use public,private or protected for our methods.

2. In PHP4 there are interfaces but no abstract or final keyword.

An interface can be implemented by any object and which means that all the functions of interface must be implemented by the object.We can only declare the name and access type of any method in an interface.

An abstract class is where some methods may have some body too.

A final class cannot be extended.

3. In PHP4 there is no multiple inheritances for interfaces but Php5 supports multiple inheritance via implementing multiple interfaces together.

4. In PHP4 everything is static i.e if we declare any method in class which uses $this keyword we can call the same via classname::method() i.e. without instantiating the class which is not allowed in PHP5.

5. There is no class based constant,static property,destructor in PHP 4.

6. PHP 4 allows shallow copy of object.But in PHP 5 shallow copy is possible only via clone keyword.

7. PHP 4 does not have an exception object where as PHP 5 has an exception object.

8. Method over loading via magic functions like __get() and __set() is possible in PHP 5

OOPS-PHP-usefull functions

1. get_declared_classes();
Returns an array with the name of the defined classes.Useful when you have integrated a component or helper or vender class and what to know whether it's been included or not.

Thursday, September 12, 2013

Differences between abstract class and interface in PHP

Following are some main difference between abstract classes and interface in php
  1. In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract.
  2. Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.
  3. Method of php interface must be public only. Method in abstract class in php could be public or protected both.
  4. In abstract class you can define as well as declare methods. But in interface you can only defined your methods.

Javascript-Typecasting-Question

What will this print

<script type="text/javascript">
alert('1'+2+4);
</script>


Ans : 124(since js typcasts everthing to string if a string is encountered)


When dealing with two numbers, the + operator adds these. When dealing with two strings, it concatenates.

3 + 5;              // 8
"hello " + "world"; // "hello world"
"3" + "5";          // "35"
 
 
When one operand is a string and the other is not, the other is converted to a string and the result is concatenated. 

"the answer is " + 42; // "the answer is 42"
"this is " + true;     // "this is true"
var a;
"a is " + a;           // "a is undefined"
 
In any other case (except for Dates) the operands are converted to numbers and the results are added.
 
1 + true;     // -> 1 + 1 -> 2
null + false; // -> 0 + 0 -> 0
 
 

How can I send headers then start a session?

  <?php 

  // make it or break it 

  error_reporting(E_ALL); 

  // begin output buffering 

  ob_start(); 

  // send a header 

  header ("Pragma: no-cache"); 

  // send some text to the browser 

  echo 'This is a line of text'; 

  // then we start our session  

  session_start(); 

  // set the value of the session variable 'foo' 

  $_SESSION['foo']='bar'; 

  // flush the buffer 

  ob_end_flush(); 

 ?>  


How are sessions stored?

The default behaviour for session storage is to save the session data in a file. This behaviour can be altered by changing the session.save_handler in your php.ini file. Options can be:

1. files
2. mm
3. database
4. SQLite

If we choose we can have this stored in one of the options above.

In files  session's are stored in /var/lib/php5 in Debian based linux
file is named like "sess_v93e2jhpjho4s4ea7r93vkbvu7" and data is stored like
foo|s:3:"bar";animals|a:8:{i:0;s:3:"cat";i:1;s:3:"dog";i:2;s:5:"mouse";i:3;s:4:"bird";i:4;s:9:"crocodile";i:5;s:6:"wombat";i:6;s:5:"koala";i:7;s:8:"kangaroo";}

The mm option saves the session data into memory, this also gives significant speed increase and is often recommended by tutorials for fine tuning PHP and apache web server.

Sessions may also be stored in a database. This option provides for greater manageability of sessions and allows the programmer to perform tasks such as counting of active sessions etc.In this session storage is permanent.

With the advent of PHP5, we now have SQLite bundled with PHP. If PHP is configured --with-sqlite, you will have access to saving sessions with a PHP native database, although SQLite is not truly a database, but a file abstraction layer with and SQL interface.

php-How do sessions work?

Sessions can be used in two ways:

1. cookie based
2. url based

Most sessions are cookie based. What this means is that when a session is started, a cookie is set on the clients machine with a unique session ID or SID. The session variables are stored typically on a file on the server that matches the unique session ID. When a variable is required, the client or browser looks for the file matching the session ID and retrieves the corresponding variables from it. A typical session file stored in the default session file directory would look like this
sess_fd51ab4d1820aa6ea27a01d439fe9959

PHP-Path to Session Storage

We can get and set session storage path using the following keyword in core php

session_save_path ([ string $path ] );

Wednesday, September 11, 2013

cakephp-requestAction

The method requestAction are used in cake php for calls a controller’s action from any location and returns data from the action.

Example :

 // Controller/CommentsController.php  
 class CommentsController extends AppController {  
   public function latest() {  
     if (empty($this->request->params['requested'])) {  
       throw new ForbiddenException();  
     }  
     return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));  
   }  
 }  

 // View/Elements/latest_comments.ctp  
 $comments = $this->requestAction('/comments/latest');  
 foreach ($comments as $comment) {  
   echo $comment['Comment']['title'];  
 }  

Php-require,require_once,include,include_once

Difference between require() and require_once(): require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).

So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING. There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

Cakephp-Difference in App:Uses(),App::import(),App::path()

App::uses() loads libraries using same standrds as cakephp folder structure i.e for files which follow the same standards regarding folder and file naming.

This is why it is not advisable to load vendor's using App::uses().

App::import() loads file if it has not been included before i.e. it is just a wrapper of include_once();

App::path() return the path of concerned cakephp folder

example: App::path('Vendor') return's path of vendor

Drawbacks of cakephp

1. Can't be used for small scale apps as it loads the complete application in beginning.
2. Learning Curve

Cakephp-Why cakephp have two vendor folder?

The “vendors” folder in the “app” folder is for application-specifc third-party libraries whereas the other “vendors” folder is for libraries you want to use in multiple applications.

Cakephp-HABTM implementation

HABTM

"Has and Belongs To Many"

A "Post" may have many "Tags" and may belong to many tags

In Post's Model


 public $hasAndBelongsToMany = array(  
  'Tag' => array(  
   'className' => 'Tag',  
   'joinTable' => 'posts_tags',  
   'foreignKey' => 'post_id',  
   'associationForeignKey' => 'tag_id',  
   'unique' => 'keepExisting',  
  )  
  );  

Cakephp-What are cakephp's configuration files?

  1. /app/config/core.php=>where we manage core configuration's such as debug,use of .htaccess
  2. /app/config/database.php=>Manage database configurations
  3. /app/config/email.php=>Manage email smtp configurations
  4. /app/config/routes.php=>manage routing

Cakephp-What are commonly used components of cakephp?

1. Security
2. Sessions
3. Access control lists
4. Emails
5. Cookies
6. Authentication
7. Request handling

Cakephp-What is the naming convention in cakephp

  1. Table names are plural and lowercased
  2. Model names are singular and CamelCased: ModelName, model filenames are singular: model.php
  3. Controller names are plural and CamelCased with *Controller* appended: ControllerNamesController, controller filenames are named similerly : usersController
  4. Associations should use the ModelName, and the order should match the order of the foreignKeys: var $belongsTo = ‘User’; 
  5. Foreign keys should always be: table_name_in_singular_form_id: user_id (foreign key) → users (table),
  6. many-to-many join tables should be named: alphabetically_first_table_plural_alphabetically_second_table_plural: tags_users ,
  7. columns in many-to-many join tables should be named like other foreign keys: tag_id and user_id ,
  8. columns named “created” and “modified” will automatically be populated correctly