Google Datastore JAVA

we will discover Google Datastore Queries, in this example we will manipulate a book entity with proporties:  id, titleauthorisbndate.



So let's Start;

Create new Entity or Add new Entries:



DatastoreService datastore DatastoreServiceFactory.getDatastoreService();
 Entity entityBook new Entity("Books");        
 entityBook.setProperty("title", "title1");    
 entityBook.setProperty("author", "author1");    
 entityBook.setProperty("isbn", "12E3E31E");  
 entityBook.setProperty("date", new Date());
 datastore.put(entityBook);
In this case the id will be generated automatically by GAE.
you can use Key to manually add the ID
     Key bookKey = KeyFactory.createKey("Books", "id1");
     Entity entityBook = new Entity("books", bookKey);
     entityBook.setProperty("title", "title1");
     entityBook.setProperty("author", "author1);
     entityBook.setProperty("isbn", "12E3E31E");
     entityBook.setProperty("date",new Date() );    
     DatastoreService datastore=DatastoreServiceFactory.getDatastoreService();
     datastore.put(entityBook);
 Filters   
A query's filters set constraints on the propertieskeys, and ancestors of the entities to be retrieved.

Return 5 Books as a List.

 DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
 Query query = new Query("Books").addSort("date", Query.SortDirection.DESCENDING);
 List<Entity> customers = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
Find and returned a book with matched filter.

 Query query = new Query("Books");
 query.addFilter("title", FilterOperator.EQUAL, "title1");
 PreparedQuery pq = datastore.prepare(query);
 Entity Book = pq.asSingleEntity();
Note: The comparison operator can be any of the following (defined as enumerated constants in the nested class Query.FilterOperator):

OperatorMeaning
EQUALEqual to
LESS_THANLess than
LESS_THAN_OR_EQUALLess than or equal to
GREATER_THANGreater than
GREATER_THAN_OR_EQUALGreater than or equal to
NOT_EQUALNot equal to
INMember of (equal to any of the values in a specified list)
The NOT_EQUAL operator actually performs two queries: one in which all other filters are unchanged and the NOT_EQUAL filter is replaced with a LESS_THAN filter, and one where it is replaced with a GREATER_THAN filter. The results are then merged, in order. A query can have no more than one NOT_EQUAL filter, and a query that has one cannot have any other inequality filters.
The IN operator also performs multiple queries: one for each item in the specified list, with all other filters unchanged and the IN filter replaced with an EQUAL filter. The results are merged in order of the items in the list. If a query has more than one IN filter, it is performed as multiple queries, one for each possible combination of values in the IN lists.
A single query containing NOT_EQUAL or IN operators is limited to no more than 30 subqueries.
Update Entity:
To update, just modify the existing Entity and save it again.
 Query query = new Query("Books");
 query.addFilter("title", FilterOperator.EQUAL, "title1");
 PreparedQuery pq = datastore.prepare(query);
 Entity Book = pq.asSingleEntity();
 
 Book.setProperty("name", name);
 Book.setProperty("email", email);
 
 DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
 datastore.put(Book); //GAE will know save or update
Note: you can get an entity by the id:

         DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
               Key k=KeyFactory.createKey("Books", "id1");       
               Entity book=datastore.get(k);
 
Delete:

To delete, need the entity key.
                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                Key k=KeyFactory.createKey("Books", "id1");
                datastore.delete(k);
Note: you can search for an entity using Filters then deleted using datastore.delete(book.getKey());

For more details about datastore queries see: developers.google.com/appengine/docs/java/datastore/queries

php MVC

What Exactly is a Model-View-Controller?

A Model-View-Controller is a pattern of software architecture. It controls how different applications interact with a user.
Here’s a fun fact: you’re looking at a MVC right now.
This web page is a perfect example of the MVC structure. Here, the HTML structure of this web page is the model, the CSS stylesheets that control its appearance are the ‘View’, and the browser that you use to interact with the web page is the ‘controller’.
Let’s look at this in a little more detail:
Model: The model is a representation of knowledge. That is, the model contains the actual data that has to be shown to the user. All data is held in a structured format. For example, the HTML on this web page holds the actual text that you see inside structured HTML <tags>.
View: The view is a visual representation of the model. The view informs the way data structured in the model will be made visible to the user. For example, the HTML may hold the text, but the colors, font size and font style information is actually held by independent CSS stylesheets – i.e. the view.
Controller: A controller is the environment that bridges the divide between the user and the system. This is the device that lets the user interact with the system. In the above examples, the browser is the controller that helps you interact with the web page.
One way of representing this is as follows:

Example:
we start with defining the index
index.php:
<?php
if  ($_GET['do']=="")
{                  
  require ("default.html");
}
else
{
  if($_GET['do']=="display")
  {
    require("action/controller.php");
    new Example();
  }
}
?>

in the index we define how to display a page using "do" : static page("default.html") or redirect to the controller  "controller.php".
Controller : /action/controller.php:
<?php
 require ("dao/model.php");

  class Controller
 {
  public function cc()
  {
    $exampleDao= new ExampleDao();
    $data = $exampleDao->get_products();
    require("web/display.phtml");

  }
}
?>


Model : model.php

<?php
 require ("class_connect_bd.php");

 class Model
 {
   public  function get_products()
   {
    $sql = "SELECT product.name, product.price FROM product where product.type=42";
    $query = mysql_query($sql) or die('Erreur SQL !<br>'.mysql_error());
    $all =  mysql_fetch_all($query);
    return $all;
   }
 }
?>

in the Model we define a function that return a product proprties from the database.

class_connect_bd.php:

<?php
$db = mysql_connect('localhost', 'user', 'password');
mysql_select_db('test',$db);

 function mysql_fetch_all($query, $kind = 'assoc') {
    $result = array();
    $kind = $kind === 'assoc' ? $kind : 'row';
    eval('while(@$r = mysql_fetch_'.$kind.'($query)) array_push($result, $r);');
    return $result;
}
?>





View: /web/display.phtml:


<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">
  <head>
    <title>
      Example
    </title>
  </head>
  <body>
    <?
foreach ($data AS $row )
{
?>
   Nom :
<? echo $row["name"]; ?>
 Prix :
<? echo $row["price"]; ?> <br/>
<?
}
?>
  </body>
</html>


       Note:                                                                                                


   .PHP
 : Page doesn't contain view-related code

  .PHTML
 : Page contains little (if any) data logic and the most part of it is    

   presentation-related









Abstract classes

Abstract classes are special because they can never be instantiated. Instead, you typically inherit a set of base functionality from them in a new class. For that reason, they are commonly used as the base classes in a larger class hierarchy. In the chapter on inheritance, we created an Animal class and then a Dog class to inherit from the Animal class. In your project, you may very well decide that no one should be able to instantiate the Animal class, because it's too unspecific, but instead use a specific class inheriting from it. The Animal class will then serve as a base class for our own little collection of animals. 

Why Use Abstract Classes?

An Abstract class provides concrete base functions as well as abstract functions that must be implemented by concrete child classes—binding them into a contract so to speak, if they wish to make use of the base functionality.
This is a subtle but important point and this is where abstract classes really shine. They can call abstract functions from within base concrete functions.

A method can be marked as abstract as well. As soon as you mark a class function as abstract, you have to define the class as abstract as well - only abstract classes can hold abstract functions. Another consequence is that you don't have to (and can't) write any code for the function - it's a declaration only. You would do this to force anyone inheriting from your abstract class to implement this function and write the proper code for it. If you don't, PHP will throw an error. However, abstract classes can also contain non-abstract methods, which allows you to implement basic functionality in the abstract class. Let's go on with an example. Here is the abstract class:

abstract class Animal
{
    public $name;
    public $age;
    
    public function Describe()
    {
        return $this->name . ", " . $this->age . " years old";    
    }
    
    abstract public function Greet();
}
As you can see, it looks like a regular exception, but with a couple of differences. The first one is the abstract keyword, which is used to mark both the class it self and the last function as abstract. As mentioned, an abstract function can't contain any body (code), so it's simply ended with a semi-colon as you can see. Now let's create a class that can inherit our Animal class:
class Dog extends Animal
{
    public function Greet()
    {
        return "Woof!";    
    }
    
    public function Describe()
    {
        return parent::Describe() . ", and I'm a dog!";    
    }
}
As you can see, we implement the both functions from the Animal class. The Greet() function we are forced to implement, since it's marked as abstract - it simply returns a word/sound common to the type of animal we are creating. We are not forced to implement the Describe() function - it's already implemented on the Animal class, but we would like to extend the functionality of it a bit. Now, the cool part is that we can re-use the code implemented in the Animal class, and then add to it as we please. In this case, we use the parent keyword to reference the Animal class, and then we call Describe() function on it. We then add some extra text to the result, to clarify which type of animal we're dealing with. Now, let's try using this new class:
$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();
Nothing fancy here, really. We just instantiate the Dog class, set the two properties and then call the two methods defined on it. If you test this code, you will see that the Describe() method is now a combination of the Animal and the Dog version, as expected.

Inheritance

Inheritance is the mechanism of deriving a new class from an existing class. It allows a sub-class / child class to share/inherit the attributes and behaviors of a base-class or parent class. These inherited attributes and behaviors are usually modified by means of extension.

Imagine that you need to represent various types of animals. You could create a Cat class, a Dog class and so on, but you would probably soon realize that these classes would share quite a bit of functionality. On the other hand, there could be stuff that would have to be specific for each animal. For a case like this, inheritance is really great. The idea is to create a base class, in this case called Animal, and then create a child class for each specific animal you need. Another advantage to this approach is that you will every animal you have will come with the same basic functionality that you can always rely on. 


To inherit in PHP5, you should use the keyword ‘extends’ in the class definition. In PHP5 only single inheritance is allowed. 

Again, this can seem very theoretic and you might not find it very useful in the beginning, but as you create more advanced websites, you will likely run into situations where inheritance can come in handy. Let's have a look at an example now:

class Animal
{
    public $name;
    
    public function Greet()
    {
        return "Hello, I'm some sort of animal and my name is " . $this->name;
    }
}
A very simple class, pretty much like the ones we created in a previous chapter. However, "some sort of animal" is not very descriptive, so let's create a child class for a dog:
class Dog extends Animal
{
    
}
The dog is declared like a regular class, but after that, we use the extends keyword to tell PHP that the Dog class should inherit from the Animal class. Right now, our Dog class has the exact same functionality as the Animal class. Verify this by running the following code:
$dog = new Dog();
echo $dog->Greet();
You will see that both the name and the Greet() function is still there, but they are also still very anonymous. Let's change that by writing a specific version of the Greet() function for our Dog:
class Dog extends Animal
{
    public function Greet()
    {
        return "Hello, I'm a dog and my name is " . $this->name;
    }
}
Notice that we declare the Greet() function again, because we need for it to do something else, but the $name class variable is not declared - we already have that defined on the Animal class, which is just fine. As you can see, even though $name is not declared on the Dog class, we can still use it in its Greet() function. Now, with both classes declared, it's time to test them out. The following code will do that for us:
$animal = new Animal();
echo $animal->Greet();
$animal = new Dog();
$animal->name = "Bob";
echo $animal->Greet();
We start out by creating an instance of an Animal class and then call the Greet() function. The result should be the generic greeting we wrote first. After that, we assign a new instance of the Dog class to the $animal variable, assign a real name to our dog and then call the Greet() function again. This time, the Dog specific Greet() function is used and we get a more specific greeting from our animal, because it's now a dog. 

Inheritance works recursively as well - you can create a class that inherits from the Dog class, which in turn inherits from the Animal class, for instance a Puppy class. The Puppy class will then have variables and methods from both the Dog and the Animal class.

constant

A constant is, just like the name implies, a variable that can never be changed. When you declare a constant, you assign a value to it, and after that, the value will never change. Normally, simple variables are just easier to use, but in certain cases constants are preferable, for instance to signal to other programmers (or your self, in case you forget) that this specific value should not be changed during runtime. 

Class constants are just like regular constants, except for the fact that they are declared on a class and therefore also accessed through this specific class. Just like with static members, you use the double-colon operator to access a class constant. Here is a basic example:

<?php
class User
{
    const DefaultUsername = "John Doe";
    const MinimumPasswordLength = 6;
}

echo "The default username is " . User::DefaultUsername;
echo "The minimum password length is " . User::MinimumPasswordLength;
?>
As you can see, it's much like declaring variables, except there is no access modifier - a constant is always publically available. As required, we immediately assign a value to the constants, which will then stay the same all through execution of the script. To use the constant, we write the name of the class, followed by the double-colon operator and then the name of the constant. That's really all there is to it.

Static classes

Since a class can be instantiated more than once, it means that the values it holds, are unique to the instance/object and not the class itself. This also means that you can't use methods or variables on a class without instantiating it first, but there is an exception to this rule. Both variables and methods on a class can be declared as static (also referred to as "shared" in some programming languages), which means that they can be used without instantiating the class first. Since this means that a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods, since these require an instance of the class. 

In a previous chapter, we wrote a User class. Let's expand it with some static functionality, to see what the fuzz is all about:

<?php
class User
{
    public $name;
    public $age;
    public static $minimumPasswordLength = 6;
    
    public function Describe()
    {
        return $this->name . " is " . $this->age . " years old";
    }
    
    public static function ValidatePassword($password)
    {
        if(strlen($password) >= self::$minimumPasswordLength)
            return true;
        else
            return false;
    }
}

$password = "test";
if(User::ValidatePassword($password))
    echo "Password is valid!";
else
    echo "Password is NOT valid!";
?>
What we have done to the class, is adding a single static variable, the $minimumPasswordLength which we set to 6, and then we have added a static function to validate whether a given password is valid. I admit that the validation being performed here is very limited, but obviously it can be expanded. Now, couldn't we just do this as a regular variable and function on the class? Sure we could, but it simply makes more sense to do this statically, since we don't use information specific to one user - the functionality is general, so there's no need to have to instantiate the class to use it. 

As you can see, to access our static variable from our static method, we prefix it with the self keyword, which is like this but for accessing static members and constants. Obviously it only works inside the class, so to call the ValidatePassword() function from outside the class, we use the name of the class. You will also notice that accessing static members require the double-colon operator instead of the -> operator, but other than that, it's basically the same.
Newer Posts Older Posts
Copyright © JEsmairi
Back To Top