PDF Generation using FPDF in PHP

 FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. It is free to use and it does not require any API keys. FPDF stands for Free PDF. It means that any kind of modification can be done in PDF files.

Feature - 

- Choice of measure unit, page format and margins

- Page header and footer management

- Automatic page break

- Automatic line break and text justification

- Image support (JPEG, PNG and GIF)

- Colors

- Links

- TrueType, Type1 and encoding support

- Page compression

PHP-FPDF Code for PDF Generation - 

This code is used to generate PDF for displaying text file data. Download FPDF to execute this script.

<?php

require('fpdf/fpdf.php');

$pdf = new FPDF();

$pdf->AddPage();

$row=file('abc.txt');

$pdf->SetFont('Arial','B',12);

foreach($row as $rowValue) {

$data=explode(';',$rowValue);

foreach($data as $columnValue)

$pdf->Cell(90,12,$columnValue,1);

$pdf->SetFont('Arial','',12);

$pdf->Ln();

}

$pdf->Output();

?>

Drupal 8 routing

 A route is a path which is defined for Drupal to return some sort of content on. For example, the default front page, '/node' is a route. When Drupal receives a request, it tries to match the requested path to a route it knows about. If the route is found, then the route's definition is used to return content. Otherwise, Drupal returns a 404.

Routing system in Drupal 8 replaces hook_menu() in Drupal 7. The parts of hook_menu() that we are used for  creating menu entries, tabs, actions and contextual links are taken over by other subsystems. 

Drupal's routing system works with the Symfony HTTP Kernel. To learn the basics of Drupal 8's routing system, the Symfony Routing component's documentation is an excellent place to start. 

Routes -

A route determines which code should be run to generate the response when a URI is requested. It does this by mapping a URI to a controller class and method. This defines how Drupal deals with a specific URI.

Routes are stored in a YAML file (check out last week's tutorials on YAML files) in the root of the module and use the following naming convention.

modulename.routing.yml

Example - 

hello.content:

  path: '/hello'

  defaults:

    _controller: 'Drupal\hello\Controller\HelloController::content'

    _title: 'Hello world'

  requirements:

    _permission: 'access content'

The name of the route is hello.content. The path is /hello, which is the registered URL path. So when a user enters sitename.com/hello, this route will decide which code should be run to generate a response.

We then have two default configurations specified, the controller and the title.

The controller tells Drupal which method to call when someone goes to the URL for the page (which is defined in the route).

look at the path included in _controller.

'Drupal\hello\Controller\FirstController::content’

This comprises of a namespaces class, a double colon and then the method to call.

hello.content:

  path'/hello'

  defaults:

    _controller'Drupal\hello\Controller\HelloController::content'

    _title'Hello world'

  requirements:

    _permission'access content'

The title is the default page title. So when a user goes to /hello, the page title will be ‘Hello world’

Controllers - .

Controllers take requests or information from the user and decide how to handle the request. For this module, the controller is responsible generating the content (the ‘Hello world’ message) and returning it for the page.

A controller that returns a simple Hello world message looks like this.

<?php

/**

 * @file

 * Contains \Drupal\hello\Controller\HelloController.

 */

namespace Drupal\hello\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {

  public function content() {

    return array(

      '#type' => 'markup',

      '#markup' => t('Hello world'),

    );

  }

}

 The controller is returning a renderable array with “Hello world”. So if you hit /hello once all this is in place, you will get a Drupal page with a Hello world message.

PHP annotations

 Annotations are meta-data that can be embedded in source code.

You may already be familiar with the PHP-DOC flavor of source code annotations, which are seen in most modern PHP codebases - they look like this:

class Foo

{

  /**

   * @var integer

   */

  public $bar;

}

When you see @var integer in the source code, immediately preceding the public $bar declaration, this little piece of meta-data tells us that the $bar property is expected to contain a value of type integer.

This information is useful to programmers - an IDE can use this information to display popup hints when you’re writing code that works with an instance of Foo, documentation generators can display this information in reference material, etc.

Now imagine you had to build an HTML form that allows someone to edit a Foo object. When this information comes back from a form-post, you will need to validate that the input is in fact an integer - using the information from the @var annotation, you could abstract and automate this process, rather than having to code in by hand every time.

The same information about the type of value required for this property could have many other uses besides validation - for example, you could use it to decide what type of input to render on a form, or how to persist the value to a database column.

Using other types of annotations besides @var, you could provide more information about the $bar property - for example, you might use an annotation to specify the minimum and maximum allowed integer values of a property for validation, or define a label to be displayed next to the input on forms or in the column-header of a list of Foo objects:

class Foo

{

  /**

   * @var integer

   * @range(0, 100)

   * @label('Number of Bars')

   */

  public $bar;

}

We now have the information about the type of value, the allowed range, and the label, all associated with the Foo::$bar property member. You may have noticed a subtle difference between the @var annotation and the other two annotations in this example: the extra parentheses - we’ll get to that below.

It’s important to understand that this meta-data does not have a single predefined purpose - it is general information, which when put to use in creative ways, can be used to simplify or eliminate repetitive work, and enables you to write more elegant and reusable code.

Annotations in Drupal 8 - 

Annotations are another  new concept in Drupal 8 to wrap your head around. Annotations are 

Annotations are used by other PHP projects. For example, Symfony2 uses annotations for routing rules and Doctrine uses them for ORM related meta data. written as PHP code comments above a class or function and contain metadata about the function or class.

As it stands, Annotations are only used by the Plugin system in Drupal 8. They provide the mechanism for which Plugins are discovered by Drupal and describe their meta data.

Plugin  - 

One of the major conceptual changes in Drupal 8 is that Drupal is not aware of your code until you specifically tell it about your code.

In module development you tell Drupal about the module in a info.yml file. You tell Drupal about specific routes in route YAML files. You tell Drupal which menu links to add to the menu system in menu YAML files. Annotations are a similar concept for Plugins. Rather than having a YAML file for each plugin, you have an annotation and Drupal will automatically find (discover) the plugin.

Example plugin type - 

Blocks are the most common type of plugin in Drupal 8. But they are by no means the only type. Plugins include.

A - Blocks

B- Field Formatters

C- Views Plugins

D- Conditions 

E- Migrate Source

See Drupal.org for more information on Annotation-based plugins.

Example annotations - 

Example of an annotation for a block class.

----------------------------------------------------------

/**

 * Provides a 'Welcome' Block

 *

 * @Block(

 *   id = "welcome_block",

 *   admin_label = "Welcome block",

 * )

 */

--------------------------------------------------------

Block manager scans files looking for @Block annotation tag to find block instances.

The @Block annotation ensures that the block manager discovers this custom block and makes it available to be added to a region. The id of welcome_block is the machine name and the admin_label (Hello block) will appear in the block interface’s list of blocks.

Annotation parser - 

Annotations are read and parsed at runtime by an annotation engine. Drupal 8 uses the Doctrine annotation parser, which turns it into an object that PHP can use.


Dependency Injection

 Dependency injection is a technique whereby one object supplies the dependencies of another object 

 What is Dependency Injection — Wikipedia

Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.

There are many ways to inject objects

Constructor Injection - 

In this we can inject an object through the class constructor.

Example - 

<?php

   class Developer{

      private $skills;

      public function __construct($skills){

         $this->skills = $skills;

      }

      public function totalSkills(){

         return count($this->skills);

      }

   }

   $createskills = array["Drupal", "Zend", "JavaScript"];

   $p = new Developer($createskills);

   echo $p->totalSkills();

?>

Setter Injection - 

Where you can inject the object to your class through setter function.

<?php

   class Multilingual {

      private $language;

      public function setLanguage($language){

         $this->language = $language;

      }

   }

   $multi = new Multilingual();

   $language = array["Drupal","Zend","JavaScript"];

   $multi->setLanguage($language);

?>

Dependency Injection Drupal - 

As of Drupal 8, dependency injection is the preferred method for accessing and using services and should be used whenever possible. Rather than calling out to the global services container, services are instead passed as arguments to a constructor or injected via setter methods. This allows for a loose coupling of components, which makes things easier to test, and easier to replace with alternative implementations.

Dependency injection (DI) and the Symfony service container are important new development features of Drupal 8. However, even though they are starting to be better understood in the Drupal development community, there is still some lack of clarity about how exactly to inject services into Drupal 8 classes.

Example - 

$service = \Drupal::service('service_name');

1. injecting services into another of your own services

2. injecting services into non-service classes

3. injecting services into plugin classes

Services - 

Injecting services into your own service is very easy. Since you are the one defining the service, all you have to do is pass it as an argument to the service you want to inject. Imagine the following service definitions.

services:

    demo.demo_service:

        class: Drupal\demo\DemoService

    demo.another_demo_service:

        class: Drupal\demo\AnotherDemoService

        arguments: ['@demo.demo_service']


Here we define two services where the second one takes the first one as a constructor argument. So all we have to do now in the AnotherDemoService class is store it as a local variable.

class AnotherDemoService {

  /**

 * @var \Drupal\demo\DemoService

   */

  private $demoService;

  public function __construct(DemoService $demoService) {

    $this->demoService = $demoService;

  }

  // The rest of your methods

}

And that is pretty much it. It's also important to mention that this approach is exactly the same as in Symfony, so no change here.

Controllers - 

Controller classes are mostly used for mapping routing paths to business logic. They are supposed to stay thin and delegate heavier business logic to services. Many extend the ControllerBase class and get some helper methods to retrieve common services from the container. However, these are returned statically.

When a controller object is being created 'ControllerResolver::createController', the ClassResolver is used to get an instance of the controller class definition. The resolver is container aware and returns an instance of the controller if the container already has it. Conversely, it instantiates a new one and returns that. 

And here is where our injection takes place: if the class being resolved implements the ContainerAwareInterface, the instantiation takes place by using the static create() method on that class which receives the entire container. And our ControllerBase class also implements the ContainerAwareInterface.

/**

 * Defines a controller to list blocks.

 */

class BlockListController extends EntityListController {

  /**

   * The theme handler.

   *

   * @var \Drupal\Core\Extension\ThemeHandlerInterface

   */

  protected $themeHandler;

 

  /**

   * Constructs the BlockListController.

   *

   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler

   *   The theme handler.

   */

  public function __construct(ThemeHandlerInterface $theme_handler) {

    $this->themeHandler = $theme_handler;

  }

  /**

   * {@inheritdoc}

   */

  public static function create(ContainerInterface $container) {

    return new static(

      $container->get('theme_handler')

    );

  }

}

The EntityListController class doesn't do anything for our purposes here, so just imagine that BlockListController directly extends the ControllerBase class, which in turn implements the ContainerInjectionInterface.

As we said, when this controller is instantiated, the static create() method is called. Its purpose is to instantiate this class and pass whatever parameters it wants to the class constructor. And since the container is passed to create(), it can choose which services to request and pass along to the constructor. 

Then, the constructor simply has to receive the services and store them locally. Do keep in mind that it's bad practice to inject the entire container into your class, and you should always limit the services you inject to the ones you need. And if you need too many, you are likely doing something wrong.

We used this controller example to go a bit deeper into the Drupal dependency injection approach and understand how constructor injection works. There are also setter injection possibilities by making classes container aware, but we won't cover that here. Let's instead look at other examples of classes you may interact with and in which you should inject services.

PHP - Traits

 PHP support only single inheritance. Traits are a mechanism for code reuse in single inheritance languages such as PHP. A trait is intended to reduce some limitation of single inheritance by enabling a developer to reuse set of method freely in several independent classes living in different class hierarchies.

PHP support only single inheritance : A child class can inherit only from one single parent. 

If a class need multiple behaviors - OOPS traits solve this problem.  

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Traits are declared with the trait keyword:

Syntax - 

<?php
trait TraitName {
  // some code...
}
?>

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

<?php
class Base {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait 
SayWorld {
    public function 
sayHello() {
        
parent::sayHello();
        echo 
'World!';
    }
}

class 
MyHelloWorld extends Base {
    use 
SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

Multiple traits - 

Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.

<?php
trait Hello {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait 
World {
    public function 
sayWorld() {
        echo 
'World';
    }
}

class 
MyHelloWorld {
    use 
HelloWorld;
    public function 
sayExclamationMark() {
        echo 
'!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to choose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the as operator can be used to add an alias to one of the methods. Note the as operator does not rename the method and it does not affect any other method either.

<?php
trait {
    public function 
smallTalk() {
        echo 
'a';
    }
    public function 
bigTalk() {
        echo 
'A';
    }
}

trait 
{
    public function 
smallTalk() {
        echo 
'b';
    }
    public function 
bigTalk() {
        echo 
'B';
    }
}

class 
Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
    }
}

class 
Aliased_Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
        
B::bigTalk as talk;
    }
}
?>

PHP use Keyword

 The use keyword has two purposes: it tells a class to inherit a trait and it gives an alias to a namespace.

Consider a case where you have two classes with the same name; you'll find it strange, but when you are working with a big MVC structure, it happens. So if you have two classes with the same name, put them in different namespaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.

Example - 

create a trait and use it in a class

<?php
trait message1 {
  public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();
?>

Another example - 

namespace SMTP;

class Mailer{}

And

namespace Mailgun;

class Mailer{}

And if you want to use both Mailer classes at the same time then you can use an alias.

use SMTP\Mailer as SMTPMailer;

use Mailgun\Mailer as MailgunMailer;

Later in your code if you want to access those class objects then you can do the following:

$smtp_mailer = new SMTPMailer;

$mailgun_mailer = new MailgunMailer;

It will reference the original class.

Some may get confused that then of there are not Similar class names then there is no use of use keyword. Well, you can use __autoload($class) function which will be called automatically when use statement gets executed with the class to be used as an argument and this can help you to load the class at run-time on the fly as and when needed.

PHP Namespace

 Namespaces are programming language mechanism for organizing function, variable and classes. PHP 5.3 add support for namespace. Namespaces solve two different problems.

1-  They allow for better organization by grouping classes that work together to perform a task

2- They allow the same name to be used more than one class

Example - you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.

Declaring a namespace - 

namespace are declared at the beginning of a file sing the namespace keyword.

syntax - 

namespace HTML;

Note - 

 A namespace declaration must be the first thing in the PHP file. The following code would be invalid:

<?php

echo "Hello PHP";

namespace HTML;

.........

?>

Constants, classes and functions declared in this file will belong to the Html namespace:

Example - 

Create a Table class in the Html namespace:

<?php
namespace Html;
class Table {
  public $title = "";
  public $numRows = 0;
  public function message() {
    echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
  }
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>

<!DOCTYPE html>
<html>
<body>

<?php
$table->message();
?>

</body>
</html>

For further organization, it is possible to have nested namespaces:

syntax - 

Declare a namespace called Html inside a namespace called Code:

namespace Code\Html;

Using Namespaces - 

Any code that follows a namespace declaration is operating inside the namespace, so classes that belong to the namespace can be instantiated without any qualifiers. To access classes from outside a namespace, the class needs to have the namespace attached to it.

Example - 

Use classes from the Html namespace:

$table = new Html\Table()
$row = new Html\Row();

When many classes from the same namespace are being used at the same time, it is easier to use the namespace keyword:

Example - 

Use classes from the Html namespace without the need for the Html\qualifier:

namespace Html;
$table = new Table();
$row = new Row();

Namespace Alias - 

It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword:

Example -

given a namespace alias 

use Html as H;
$table = new H\Table();


---------------------------

use Html\Table as T;
$table = new T();


PHP echo and print Statements

 In PHP echo and print are both used for output the data to the screen. The echo and print statements, are not function but are language constructs. 

The difference between echo and print are small : echo has no return value while print has a return value 1.  so it can be used in expression. 

echo can take multiple parameters while print can take one parameters. 

echo is marginally faster tha print.

echo Statement -

the echo statement can be used with or without  parentheses echo or echo ().

<?php

echo "<h2>PHP is Fun!</h2>";

echo "Hello world!<br>";

echo "I'm about to learn PHP!<br>";

echo "This ", "string ", "was ", "made ", "with multiple parameters.";

echo ("This ", "string ", "was ", "made ", "with multiple parameters.");

?> 


print statement -

print statement can be used with or without parenthesis: print or print().

<?php
$txt1 = "Learn PHP";
$txt2 = "wartalab.blogspot.com";
$x = 5;
$y = 4;

print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>

PHP variables scope

 In PHP , Variables can be declared anywhere in the script. The scope of a variable is the context within which it is defined.

PHP has three different variable scope.

A- Global

B- Local

C- Static


Local and Global Scope

<?php
$a 
1;
include 
'b.inc';
?>

 Here $a variable available within the included 'b.inc' file

<?php

$m = 5// global scope

function variableTest() {
  // using m inside this function will generate an error
  echo "<p>Variable m inside function is: $m</p>";
}
variableTest();

echo "<p>Variable m outside function is: $m</p>";
?>

A variable declared outside a function has a Global Scope and can only be accessed outside function. 

<?php
function variableTest() {
  $m = 5// local scope
  echo "<p>Variable m inside function is: $m</p>";
}
variableTest();

// using m outside the function will generate an error
echo "<p>Variable m outside function is: $m</p>";
?>

A Variable declared within a function has a local scope and can be accessed only within that function.

The global keyword

The global keyword is used to access a global variable from within a function.

For this use global keyword before the variable (inside the function).

<?php
$a 
1;
$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;


Sum();
echo 
$b; // output 3
?>

PHP also store all global variable in an array $GLOBALS[index]. The index hold name of the variable. This array is also accessible within that function.

The above example can be written like this.

<?php
$a 
1;
$b 2;

function 
Sum()
{
  


    
$GLOBALS['b'] $GLOBALS['a'] $GLOBALS['b'];


Sum();
echo 
$b; // output 3
?>

The static Keyword

Another important feature of variable scoping is the static variable.

Normally when a function executed/completed, all of its variable deleted. Sometimes we want to need local variable not to be deleted or not lose.

To do this use static keyword when you first declare the variable.

Example -

<?php
function variableTest() {
  static $x = 0;
  echo $x;
  $x++;
}

variableTest();   // output 0
variableTest();   // output 1
variableTest();   // output 2
?>

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...