Monday, 17 October 2016

Memcache Vs. Memcached


I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
The Memcache module also provides a session handler (memcache).

MemcacheD s a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

They are not identical. Memcache is older but it has some limitations. I was using just fine in my application until I realized you can't store literal FALSE in cache. Value FALSE returned from the cache is the same as FALSE returned when a value is not found in the cache. There is no way to check which is which. Memcached has additional method (among others) Memcached::getResultCode that will tell you whether key was found.
Because of this limitation I switched to storing empty arrays instead of FALSE in cache. I am still using Memcache, but I just wanted to put this info out there for people who are deciding.

Sunday, 16 October 2016

Multiple memcached servers question


hypothetically - if I have multiple memcached servers like this:
//PHP 
$MEMCACHE_SERVERS = array(
    "10.1.1.1", //web1
    "10.1.1.2", //web2
    "10.1.1.3", //web3 
); 
$memcache = new Memcache();
foreach($MEMCACHE_SERVERS as $server){
    $memcache->addServer ( $server ); 
}
And then I set data like this:
$huge_data_for_frong_page = 'some data blah blah blah';
$memcache->set("huge_data_for_frong_page", $huge_data_for_frong_page);
And then I retrieve data like this:
$huge_data_for_frong_page = $memcache->get("huge_data_for_frong_page");
When i would to retrieve this data from memcached servers - how would php memcached client know which server to query for this data? Or is memcached client going to query all memcached servers?

   Solution :

Well you could write books about that but the baseic principle is that there are some different approaches.
The most common and senseful approach for caching is sharding. Which means the data is sotred only on one server and some method is used to determining which server this is. So it can be fetched from this very server and only one server is involved.
This obviously works well in key/value environments as memcached.
A common practice is to take a cryptographical hash of the key. Calculate this hash MOD number of servers and the result is the server you will store and fetch the data.
This procedure produces more or less equal balancing.
How its exactly done in memcached i dunno but some sort of hash for sure.
But beware that this teqnique is not highly available. So if one server fails the entries are gone. So you obviously can only use this for caching purposes.
Other teqniques, where for example high availability of resources is necessary, that take long to calculate and are automatiaclly warmed up int he background, involve replication.
The most common form in caching environments is master-master replication with latest-timestamp conflict resolving. Which bascically means every server gets the data from everyserver that is not yet on the local server (this is done using replication logs and byte offsets). If there is a conflict the latest version is used (the slight time offset between servers is ignored).
But in other environments where for examply only very little is written but a lot is read there is often a cascade where only one or few master servers are involved and the rest is just pure read replication.
But theese setups are very rare because sharding as describeda bove gives the best performance and in caching environments data loss is mostly tolerable. so its also default for memcached.

Memcached and other caching

Here are a few notes about some of the technologies you have mentioned above.

Memcached:

Memcached is only a caching system and will not provide you with any data persistence. If you choose to use memcached then you will need to choose some other type of persistent store to keep all of you data. Memcached is also a very simple caching system and does not provide you with replication, but their are different project (like repcache) that have added features like this to memcached. I would only use memcached if I wanted to use a relational database as my persistence layer.

Redis:

Redis is a data structure server and should only be used for that purpose. The downside to Redis is that you can only run it on a single server and if you want to have multiple servers of Redis then you need to do application sharding. Most of the deployments of Redis I have seen are along side another database technology.

Couchbase:

Couchbase 2.0 will will turn the product into a document database. The product has memcached technology inside it so you get memcached out of the box which means sub-millisecond latencies. On top of this you get replication, cross data center replication and querying support. Also, note that most Couchbase SDK's don't use moxi and that the Python SDK is still in beta.
One thing that might be useful for you to do is to check out the YCSB benchmarking project along with some of the results that have already been published. This project will allow you to get a good idea of how these and other databases perform under load. Then once you find some you like you can look through their feature list and figure out with product has the features that best fits the application your developing.
Also, if any of my information about the databases above is incorrect please let me know. These projects are evolving quickly and sometimes it's hard to keep up.
EDIT: I should also mention that Couchbase is the only databases out of the ones listed that provide replication, sharding, and low latency. I imagine redis will allow you to have a replica server and therefore replication, but any sharding you do will have to be done at the application layer

Ajax - Cross Domain working wiht JSONP

Same-origin Policy

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, however they’re restricted in what they can do by the same origin-policy. This is an important concept in the browser security model and dictates that a web browser may only allow scripts on page A to access data on page B if these two pages have the same origin. The origin of a page is defined by its protocol,host and port number. For example the origin of this page is ‘https’, ‘www.sitepoint.com’, ’80’.
The same-origin policy is a saftey mechanism. It prevents scripts from reading data from your domain and sending it to their servers. If we didn’t have this, it would be easy for a malicious website to grab your session information to another site (such as Gmail or Twitter) and execute actions on your behalf. Unfortunately, it also causes the error we see above and often poses a headache for developers trying to accomplish a legitimate task.

A failing example

Let’s look at what doesn’t work. Here’s a JSON file residing on a different domain which we would like to load using jQuery’sgetJSON method.
$.getJSON(
  "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
  function(json) { console.log(json); }
);
If you try that out in your browser with an open console, you will see a message similar to the one above. So what can we do?

A Possible Workaround

Luckily, not everything is affected by the same-origin policy. For example, it is quite possible to load an image or a script from a different domain into your page—this is exactly what you are doing when you include jQuery (for example) from a CDN.
This means that we are able to create a <script> tag, set the src attribute to that of our JSON file and inject it into the page.
var script = $("<script />", {
    src: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
    type: "application/json"
  }
);

$("head").append(script);
Although that works, it doesn’t help us much, as we have no way of getting at the data it contains.

Enter JSONP

JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data. It does this by having the server return JSON data wrapped in a function call (the “padding”) which can then be interpreted by the browser. This function must be defined in the page evaluating the JSONP response.
Let’s see what that would look like with our previous example. Here’s an updated JSON file which wraps the original JSON data in a jsonCallback function.
function jsonCallback(json){
  console.log(json);
}

$.ajax({
  url: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json",
  dataType: "jsonp"
});
This logs the expected result to the console. We now have (albeit rather limited) cross-domain Ajax.

3rd Party APIs

Some 3rd party APIs let you specify a name for the callback function which should be executed when the request returns. One such API is the GitHub API.
In the following example we’re getting the user information for John Resig (jQuery creator) and using a logResultscallback function to log the response to the console.
function logResults(json){
  console.log(json);
}

$.ajax({
  url: "https://api.github.com/users/jeresig",
  dataType: "jsonp",
  jsonpCallback: "logResults"
});
This can also be written as:
$.getJSON("https://api.github.com/users/jeresig?callback=?",function(json){
  console.log(json);
});
The ? on the end of the URL tells jQuery that it’s dealing with a JSONP request instead of JSON. jQuery then automatically registers the callback function which it calls when the request retruns.
If you’d like to learn more about jQuery’s getJSON method, check out: Ajax/jQuery.getJSON Simple Example

Caveats

But as you might have realized by now, there are some drawbacks to this approach.
For example, JSONP can only perform cross-domain GET requests and the server must explicitly support it. JSONP is also not without its security concerns, so let’s briefly look at some other solutions.

Using a proxy

Server-side code is not bound by the same origin policy and can perform cross-origin requests without a problem. You could therefore make some kind of proxy and use that to retrieve whatever data you need. With reference to our first example:
/* proxy.php */
$url = "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
curl_close ($ch);
echo $result;
And on the client side:
$.getJSON("http://my-domain.com/proxy.php", function(json) {
  console.log(json);
})
But this approach also has its downsides. For example, if the third-party site uses cookies for authentication, this will not work.

CORS

Cross-Origin Resource Sharing (CORS) is a W3C spec to allow cross-domain communication from the browser. This is done by including a new Access-Control-Allow-Origin HTTP header in the response.
With reference to our first example, you could add the following to a .htaccess file (assumes Apache) to permit requests from a different origins:
Header add Access-Control-Allow-Origin "http://my-domain.com"
(If you have a server running something other than Apache, look here: http://enable-cors.org/server.html)
You can find out more about CORS in one of our recent tutorials: An In-depth Look at CORS

Conclusion

JSONP allows you to sidestep the same-origin policy and to some extent make cross-domain Ajax calls. It’s not a silver bullet, and it certainly has its issues, but in some cases it can prove invaluable when fetching data from a different origin.
JSONP also makes it possible to pull in a variety of content from different services. Many prominent sites provide JSONP services (for example Flickr), allowing you access to their content via a predefined API. You can find a comprehensive list of them in the ProgrammableWeb API directory.

Saturday, 15 October 2016

Abstract and Interface

What is abstract Classes

As from name it seem like something that is hidden. Yes nature of the abstract classes are same. Abstract classes are those classes which can not be directly initialized. Or in other word we can say that you can not create object of abstract classes. Abstract classes always created for inheritance purpose. You can only inherit abstract class in your child class. Lots of people say that in abstract class at least your one method should be abstract. Abstract method are the method which is only defined but declared. This is not true definition as per my assumption. But your any class has at least one method abstract than your class is abstract class.
Usually abstract class are also known as base class. We call it base class because abstract class are not the class which is available directly for creating object. It can only act as parent class of any normal class. You can use abstract class in class hierarchy. Mean one abstract class can inherit another abstract class also.

Abstract classes in PHP

Abstract classes in php are simillar like other oop languages. You can create abstract classes in php using abstract keyword. Once you will make any class abstract in php you can not create object of that class.
abstract class abc
{
public function xyz()
{
return 1;
}
}
$a = new abc();//this will throw error in php

above code will throw error in php.
Abstract classes in php are only for inheriting in other class.
abstract class testParent
{
public function abc()
{
//body of your funciton
}
}
class testChild extends testParent
{
public function xyz()
{
//body of your function
}
}
$a = new testChild();

In above example you are creating of testChild Class. TestChild class is inheriting testParent abstract class. So your abstract class is only available for inheritance. Main motive of creating abstract classes in php is to apply restriction of direct initialization or object creation.

Implementation of abstract method

As we know that abstract functions are those functions of abstract class which is only defined. It will be declared in your child class. You can create any method abstract using keyword abstract. You can only create abstract method either in abstract class or interface. Following is example of the abstract method implementation:
abstract class abc
{
abstract protected function f1($a , $b);
}
class xyz extends abc
{
protected function f1($name , $address)
{
echo "$name , $address";
}
}
$a = new xyz();
In class abc we have defined an abstract function f1. Now when we have inherited class abc then declared function f1. If you have an abstract method in your abstract class then once you inherit your abstract class then it is necessary to declare your abstract method. If you will not declare your abstract method then PHP will throw error in that case.
You can declare your abstract method in child class with the same visibility or less restricted visibility.
abstract class parentTest
{
abstract protected function f1();
abstract public function f2();
//abstract private function f3(); //this will trhow error
}
class childTest
{
public function f1()
{
//body of your function
}
public function f2()
{
//body of your function
}
protected function f3()
{
//body of your function
}
}
$a = new childTest();
In above code you can see that you have declare 3 function in abstract class. But private declaration of the abstract method will always throw error. Because private method is availabe only in the same class context. But in case of f1. This is protected. Now in child class we have defined it as public because public is less restricted than protected. And for function f2 which is already public so we have defined it as public in our child class. We have defined it public because no any visibility is less restricted than public.

What is Interface ?

Interface in oop enforce definition of some set of method in the class. By implementing interface you are forcing any class to must declaring some specific set of methods in oop. For example if you are creating class to render HTML element then it is necessary to set id and name of your html tag. So in this case you will create interface for that class and define method like setID and setName. So whenever someone will create any class to render HTML tag and implemented your interface then he must need to define setId and setName method in their class. In other word you can say that by help of interface you can set some definition of your object. Interface is very useful if you are creating architecture of any oop base application. Inter

Interface in PHP

Interface in php can be implemented like other oop lanugage. You can create interface in php using keyword interface. By implementation of interface in php class you are specifying set of the method which classes must implement.
You can create interface in php using interface keyword. Rest of the things are typically identical to classes. Following is very small example of interface in php.
interface abc
{
public function xyz($b);
}

So in above code you are creating interface with name abc. Interface abc has function xyz. Whenever you will implement abc interface in your class then you have to create method with name xyz. If you will not create function xyz then it will throw error.
You can implement your interface in your class using implements keyword. Let us implement our interface abc in our class
class test implements abc
{
public function xyz($b)
{
//your function body
}
}
You can only define method in interface with public accessibility. If you will use other than public visibility in interface then it will throw error. Also while defining method in your interface do not use abstractkeyword in your methods.
You can also extend interface like class. You can extend interface in php using extends keyword.
interface template1
{
public function f1();
}
interface template2 extends template1
{
public function f2();
}
class abc implements template2
{
public function f1()
{
//Your function body
}
public function f2()
{
//your function body
}
}

So here template2 has all property of tempate2. So whenever you will implement template2 in your class, you have to create function of both interfaces.
You can also extend multiple interface in one interface in php.
interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
interface template3 extends template1, template2
{
public function f3();
}
class test implements template3
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
public function f3()
{
//your function body
}
}
You can also implement more than one interface in php class.
interface template1
{
public function f1();
}
interface template2
{
public function f2();
}
class test implments template1, template2
{
public function f1()
{
//your function body
}
public function f2()
{
//your function body
}
}

You can not implement 2 interfaces if both share function with same name. It will throw error.
Your function parameter in class must be identical to the parameter in the interface signature. Following is example some example
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($a)
{
echo $a;
}
}

Above will work. But following example will not work:
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1()
{
echo $a;
}
}

But it is not necessary to use the same name of the variable. Like $a. You can also use any name. For example:
interface template1
{
public function f1($a)
}
class test implements template1
{
public function f1($name)
{
echo $name;
}
}

If you are using default argument then you can change your value of the argument. For example
interface template1
{
public function f1($a = 20)
}
class test implements template1
{
public function f1($name  = "ankur")
{
echo $name;
}
}
In above section we have discussed interfaces and abstract classes in php. Both are almost doing same things but has some difference.

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.

Abstraction

Abstraction means providing the essential features without showing its inner details or hiding internal implementation

Abstraction : you'll never buy a "device", but always buy something more specific : iPhone, GSII, Nokia 3310... Here, iPhone, GSII and N3310 are concrete things, device is abstract.
Encapsulation : you've got several devices, all of them have got an USB port. You don't know what kind of printed circuit there's back, you just have to know you'll be able to plug an USB cable onto.
Abstraction is a concept, which is allowed by encapsulation. My exemple wasn't the best one (there's no real link between the two blocks).
You can do encapsulation without using abstraction, but if you wanna use some abstraction in your projets, you'll need encapsulation.

Consider the below real time example:
Let’s imagine you own a Ferrari Car and you are the only one knows how to drive it in your family. One day a terrible breakdown happened to your car and you bring one mechanic to home and he checked it. But he is unable to repair it. So you contacted Ferrari company and some chief mechanic came to your home and repaired it(Since your car is under warranty, your pocket is still big :-))This is a real time example for the above mentioned OOP's concepts, How?
Encapsulation:
As a driver you know how to start the car by pressing the start button and internal details of the starting operations are hidden from you. So the entire starting process is hidden from you otherwise we can tell starting operation is encapsulated from you.
OR
The driving wheel is encapsulated the process of rotating the wheel from you.
Abstraction:
Before mentioning anything about abstraction, we can take three different users here (I am calling them as entity)
1) You 2) Local Mechanic 3) Expert
You Entity: Since you know only to start the car by pressing a button and all other operations behind the scene are abstracted from you.
Local Mechanic Entity: Our local mechanic knows some of the implementation of starting the car, i.e. he can open car's bonnet and check the battery cable or chock etc. So in short Local Mechanic Entity knows some of the implementations of the car.
Expert Entity: Since our expert (Designer of the car) mechanic knows all the operations of our car, he can repair it very quickly. So in short Expert Entity knows all the implementations of the car.
The car's operation is completely abstracted from you and it is partially implemented to Local Mechanic Entity and fully implemented to Expert Entity. So you are an abstract class having only abstract methods, Local Mechanic Entity has extended You(Since he is also an ordinary user) and he implemented some of the methods and last our expert Entity extending Local Mechanic and implementing all the methods.
Also in terms of complexity "Whenever abstraction decreases, complexity increases"(Since our Expert Entity has very less abstraction, his complexity of work also increases)
In Java, garbage collection is also a best example for explaining abstraction.
As a java programmer GC is abstracted completely from you and as a language designer, one needs to understand the internal details of the JVM.
Hope this Helps!!