php apis - leanpub

20
PHP APIs Rapid Learning & Just In Time Support

Upload: others

Post on 25-Nov-2021

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PHP APIs - Leanpub

PHP APIs Rapid Learning & Just In Time Support

Page 2: PHP APIs - Leanpub

CONTENT 1 INTRODUCTION ............................................................................................................................... 3

1.1 Create PHP Application ........................................................................................................... 4

1.1.1 Create PHP Console Application ............................................................................................ 4

1.1.2 Create PHP Web Application.................................................................................................. 4

2 DATA BASE ...................................................................................................................................... 5

2.1 Oracle ..................................................................................................................................... 7

2.1.1 Connect .................................................................................................................................. 8

2.1.2 Select ...................................................................................................................................... 8

2.1.2.1 From Dual .................................................................................................................................. 8

2.1.2.2 From Table ................................................................................................................................ 9

2.1.2.3 Prepared Statement .................................................................................................................. 9

2.1.3 Insert .................................................................................................................................... 10

2.1.3.1 Prepared Statement ................................................................................................................ 10

2.1.4 Update .................................................................................................................................. 11

2.1.4.1 Prepared Statement ................................................................................................................ 11

2.1.5 Delete ................................................................................................................................... 12

2.1.5.1 Prepared Statement ................................................................................................................ 12

3 XML ............................................................................................................................................... 13

3.1 XML_Beautifier ..................................................................................................................... 13

3.1.1 Install .................................................................................................................................... 13

3.1.2 Format XML File ................................................................................................................... 14

3.1.3 Format XML String ............................................................................................................... 15

3.1.4 Format XML String with Options .......................................................................................... 16

4 ERRORS ......................................................................................................................................... 18

4.1 ReadBeanPHP ....................................................................................................................... 19

4.1.1 Could not connect to database ............................................................................................ 19

4.1.2 Unable to load dynamic library ............................................................................................ 20

Page 3: PHP APIs - Leanpub

1 Introduction

Info

This book contains tutorials about different PHP APIs.

Library is a set of all classes and functions that can be used from our code to do our task easily. Library contains some of

its private functions for its usage which it does not want to expose.

API stands for Application Programming Interface.

API is a part of library which is exposed to the user, classes and functions that programmer can use to solve specific

problem. So whatever documentation we have regarding a library, we call it an API Documentation because it contains

only those classes and functions to which we have access.

Most APIs covered in this book are used to work with data bases.

But there are also others that cover functionality needed to work with XML files, Web Services, Web Forms,

Authentication and Templating Engines.

This book presumes that reader already knows how to use PHP Programming Language.

If this is not the case reader can make him self familiar with PHP syntax by reading Rapid Learning PHP Syntax.

Meaning of symbols used in tutorials

In most tutorials you will find symbols like [R], [E] and [C] whose meanings are described in following table.

Symbols

SYMBOL NAME DESCRIPTION

[R] Reference Link to reference which was used while creating tutorial.

[E] Error Link to solution for an error that might occur while following tutorial.

[C] Create application Link to a tutorial which shows how to create an application in order to test tutorial's code.

Chapters organization

Chapters 1

First chapter contains where short tutorials that show how to run PHP application.

These tutorials will be referenced with [C] hyperlink and can be used to run and test code explained in tutorial.

How to install PHP, Web Server or IDE is explained in the first book of the series called Rapid Learning PHP Syntax.

Chapters 2 - 7

Chapters from 2 till 7 explains one or more APIs that are related to specific functionality like working with XML files, Web

Services, Web Forms, Authentication and Templating Engines.

Chapter 8

Last chapter contains list of errors that might occur while working with PHP and how to solve them.

Page 4: PHP APIs - Leanpub

1.1 Create PHP Application

Info

Following tutorials shows how to create either

● PHP Console Application which is executed through Command Prompt and doesn't need Web Server

● PHP Web Application which needs to be located in a directory accessible through web server

1.1.1 Create PHP Console Application

Info

This tutorial shows how to create PHP Console Application.

PHP Console Application is executed through Command Prompts and doesn't need Web Server.

Procedure

Create C:\Temp\Test.php.

Start MSDOS

cd C:\Temp

php Test.php

Test.php

<?php echo "Hello from PHP Console Application"; ?>

1.1.2 Create PHP Web Application

Info

This tutorial shows how to create PHP Web Application.

PHP Web Application needs to be located in a directory accessible through web server.

Procedure

Create C:\Inetpub\wwwroot\Test.php.

Start Web Browser

Address: http://localhost/Test.php

Test.php

<?php echo "Hello from PHP Web Application"; ?>

Page 5: PHP APIs - Leanpub

2 Data Base

Info

Following tutorials shows different PHP APIs used for working work with different Data Bases (DB).

Which API to use

For each DB you can choose to use few different APIs.

Most PHP programmers work with MySQL DB while using MySQL API.

But MySQL API doesn't support prepared statements so you might want to switch to MySQLi which does.

Unfortunately code written using either MySQL or MySQLi API can't be used for other data bases.

If you want to write code which will be universal for many data bases you can try using PDO API.

PDO uses the same functions to work with different DBs, supports prepared statements, transactions and other cool stuff.

And if you are into science fiction you can even try DOCTRINE which doesn't even use SQL.

Instead you work only with PHP objects and DOCTRINE takes care of storing them into actual DB.

You "just" have to write XML files which define how to store objects into DB tables.

PDO vs ADODB

PDO is likely to run faster.

PDO is included in PHP from version 5.5.

ADODB supports a larger number of databases than PDO.

DBAL

DBAL stand for Database Abstraction Layer.

DBAL is any API which allows you to call functions instead of creating SQL queries.

Such function then uses its input parameters to construct SQL query and execute it on DB.

This can be useful for following reasons

● Programmer doesn't need to know SQL, instead it can simply use his favourite programming language and ORM API

functions for working with DB.

● DBAL API allows you to use the same classes/functions to work with different Data Bases.

This means that the same code would work for MySQL, Oracle, SQLite and other Data Bases.

This is in contrast of using for instance MySQL API which works only with MySQL DB.

Code written with MySQL API must be rewritten to work with Oracle or some other DB.

Examples of DBAL APIs are

● Doctrine DBAL for PHP

● Hibernate for JAVA.

Page 6: PHP APIs - Leanpub

ORM

ORM stands for Object Relational Mapping.

ORM is any API which allows you to store Objects into Tables.

This means that ORM is used when working with OOP language and transactional DB.

This is accomplished by mapping Objects to Tables and their properties to columns.

This way ORM knows in which table to store object and which property should be stored in which column.

ORM is usually built on some DBAL API.

The two most popular implementations of ORM are

● Active Record

● Data Mapper

Active Record Pattern

With Active Record Pattern you can simple call the save() method on the object to update the database.

Each model object inherits from a base Active Record object and so you have access to all methods relating to persistence

This makes the Active Record style very easy to get started with because it is very intuitive.

Test.php

<?php

$user = new User;

$user->username = 'philipbrown';

$user->save();

?>

Data Mapper Pattern

With Data Mapper Pattern objects are just plain PHP objects that have no knowledge of the database.

This way your objects are completely separated from the persistence layer.

This means that your objects will be lighter because they don’t have to inherit the full ORM.

This also means we can’t call the save() method on the object to persist it to the database because it doesn’t exist.

Interacting with the database is more formal because you can’t simply call save() method anywhere in the code.

Instead we need to use a completely different service known as an Entity Manager.

Test.php

<?php

$user = new User;

$user->username = 'philipbrown';

EntityManager::persist($user);

?>

Page 7: PHP APIs - Leanpub

2.1 Oracle

Info

Following tutorials shows how to use PHP to work with Oracle database.

In Oracle database you should first create user myUser and table PEOPLE which will be used throughout tutorials.

Create myUser

Login as system user.

Execute following SQL statements as Script

Create user

CREATE USER myUser IDENTIFIED BY myPassword;

GRANT CREATE SESSION,

CREATE TABLE,

CREATE SEQUENCE,

CREATE VIEW,

CREATE PROCEDURE

TO myUser

IDENTIFIED BY myPassword;

GRANT UNLIMITED TABLESPACE TO myUser;

Create Table PEOPLE

Login as myUser.

Execute following SQL statements as Script

Create table

CREATE TABLE PEOPLE (

NAME VARCHAR2(10),

AGE NUMBER (3),

BORN DATE

);

INSERT INTO PEOPLE(NAME, AGE, BORN) VALUES('Ivor', 33, TO_DATE('28.02.1976', 'DD.MM.YYYY'));

INSERT INTO PEOPLE(NAME, AGE, BORN) VALUES('John', 25, TO_DATE('28.02.1280', 'DD.MM.YYYY'));

Page 8: PHP APIs - Leanpub

2.1.1 Connect

Info [C]

This tutorial shows how to ORACLE DB.

Test.php

<?php

//CONNECT TO DB.

$conn = oci_connect('SYSTEM', 'admin', 'vori/XE');

//CHECK CONNECTION.

if (!$conn) { echo(E_USER_ERROR); }

else { echo("CONNECTED" ); }

?>

2.1.2 Select

Info

Following tutorials shows how to SELECT from ORACLE DB.

2.1.2.1 From Dual

Info [R] [C]

This tutorial shows how to SELECT from dual.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser','myPassword', 'XE');

//EXECUTE STATEMENT.

$sql = "SELECT 10 FROM DUAL";

$stmt = oci_parse ($conn, $sql);

oci_execute($stmt);

//DISPLAY RESULTS.

while ($row = oci_fetch_row($stmt)) {

print($row[0]);

}

//CLOSE DB CONNECTION.

oci_close($conn);

?>

Page 9: PHP APIs - Leanpub

2.1.2.2 From Table

Info [R] [C]

This tutorial shows how to SELECT rows from a table.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$sql = "SELECT AGE, NAME, BORN AS BIRTH FROM PEOPLE";

$stmt = oci_parse ($conn, $sql);

oci_execute($stmt);

//DISPLAY RESULTS.

while ($row = oci_fetch_assoc($stmt)) {

print( $row['NAME' ] . " " );

print( $row['AGE' ] . " " );

print( $row['BIRTH'] . "\n" );

}

//CLOSE DB CONNECTION.

oci_close($conn);

?>

2.1.2.3 Prepared Statement

Info [C]

This tutorial shows how to SELECT rows from table by using prepared statement.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$age = 20;

$born = "01.01.2005";

$sql = "SELECT NAME FROM PEOPLE WHERE AGE>:age AND BORN>TO_DATE(:born, 'DD.MM.YY')" ;

$stmt = oci_parse ($conn, $sql);

oci_bind_by_name($stmt, ":age" , $age );

oci_bind_by_name($stmt, ":born", $born);

oci_execute ($stmt);

//DISPLAY RESULTS.

while ($row = oci_fetch_assoc($stmt)) {

print( $row['NAME' ] . " " );

}

//CLOSE DB CONNECTION.

oci_close($conn);

?>

Page 10: PHP APIs - Leanpub

2.1.3 Insert

Info [C]

This tutorial shows how to INSERT row into table.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$sql = "INSERT INTO PEOPLE(NAME, AGE, BORN) VALUES('Jill', 40, TO_DATE('28.02.2007','DD.MM.YYYY'))";

$stmt = oci_parse ($conn, $sql);

oci_execute($stmt);

//CLOSE DB CONNECTION.

oci_close($conn);

?>

2.1.3.1 Prepared Statement

Info [R] [C]

This tutorial shows how to INSERT row into table using Prepared Statement.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$name = "Lily";

$age = 20;

$born = "28.02.1976 18:45:21";

$sql = "INSERT INTO PEOPLE(NAME,AGE,BORN) VALUES (:name,:age,TO_DATE(:born,'DD.MM.YY HH24:MI:SS'))";

$stmt = oci_parse ($conn, $sql);

oci_bind_by_name($stmt, ":name", $name);

oci_bind_by_name($stmt, ":age" , $age );

oci_bind_by_name($stmt, ":born", $born);

oci_execute ($stmt);

//CLOSE DB CONNECTION.

oci_close($conn);

?>

Page 11: PHP APIs - Leanpub

2.1.4 Update

Info [C]

This tutorial shows how to UPDATE rows in a table.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$sql = "UPDATE PEOPLE SET AGE=54, BORN=TO_DATE('28.02.1976','DD.MM.YYYY') WHERE NAME='John'";

$stmt = oci_parse ($conn, $sql);

oci_execute($stmt);

//CLOSE DB CONNECTION.

oci_close($conn);

?>

2.1.4.1 Prepared Statement

Info [C]

This tutorial shows how to UPDATE rows in a table.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$name = "Lily";

$age = 100;

$born = "28.02.1976 18:45:21";

$sql = "UPDATE PEOPLE SET AGE=:age, BORN=TO_DATE(:born,'DD.MM.YYYY HH24:MI:SS') WHERE NAME=:name";

$stmt = oci_parse ($conn, $sql);

oci_bind_by_name($stmt, ":name", $name);

oci_bind_by_name($stmt, ":age" , $age );

oci_bind_by_name($stmt, ":born", $born);

oci_execute ($stmt);

//CLOSE DB CONNECTION.

oci_close($conn);

?>

Page 12: PHP APIs - Leanpub

2.1.5 Delete

Info [C]

This tutorial shows how to DELETE rows from a table.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$sql = "DELETE FROM PEOPLE WHERE NAME='Jill' AND AGE>20 AND BORN>TO_DATE('24-12-1999','DD-MM-YYYY')";

$stmt = oci_parse ($conn, $sql);

oci_execute($stmt);

//CLOSE DB CONNECTION.

oci_close($conn);

?>

2.1.5.1 Prepared Statement

Info [C]

This tutorial shows how to DELETE rows from a table.

Test.php

<?php

//CREATE DB CONNECTION.

$conn = oci_connect('myUser', 'myPassword', 'XE');

//EXECUTE STATEMENT.

$name = "Jill";

$age = 100;

$born = "28.02.2001";

$sql = "DELETE FROM PEOPLE WHERE AGE=:age AND NAME=:name AND BORN>TO_DATE(:born,'DD.MM.YYYY')";

$stmt = oci_parse ($conn, $sql);

oci_bind_by_name($stmt, ":name", $name);

oci_bind_by_name($stmt, ":age" , $age );

oci_bind_by_name($stmt, ":born", $born);

oci_execute ($stmt);

//CLOSE DB CONNECTION.

oci_close($conn);

?>

Page 13: PHP APIs - Leanpub

3 XML

Info

Following chapter describe different APIs for working with PHP.

3.1 XML_Beautifier

Info

XML_Beautifier is API for formatting XML files and strings.

XML_Beautifier home page is at http://www.codediesel.com/pear/beautifying-xml-documents.

3.1.1 Install

Info

This tutorial shows how to install XML_Beautifier using PEAR.

Procedure

sudo pear install XML_Beautifier

downloading XML_Beautifier-1.2.2.tgz ...

Starting to download XML_Beautifier-1.2.2.tgz (14,587 bytes)

.....done: 14,587 bytes

downloading XML_Parser-1.3.4.tgz ...

Starting to download XML_Parser-1.3.4.tgz (16,040 bytes)

...done: 16,040 bytes

install ok: channel://pear.php.net/XML_Parser-1.3.4

install ok: channel://pear.php.net/XML_Beautifier-1.2.2

Page 14: PHP APIs - Leanpub

3.1.2 Format XML File

Info [R] [C]

This tutorial shows how to use XML_Beautifier to format XML File.

To see how to set formatting options see Format XML String – With Options.

test.php

<?php

//ADD PATH TO PEAR TO php.ini PARAMETER include_path.

set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/share/php');

//INCLUDE BAUTIFIER.

require_once "/usr/share/php/XML/Beautifier.php";

//SETUP XML_Beautifier.

$XMLBeautifier = new XML_Beautifier();

//FORMAT XML FILE.

$result = $XMLBeautifier->formatFile('unformated.xml', 'formated.xml');

if (PEAR::isError($result)) {

echo $result->getMessage();

exit();

}

?>

unformated.xml

<rootNode><foo bar = "pear">hello world!</foo></rootNode>

formated.xml

<rootNode>

<foo bar="pear">hello world!</foo>

</rootNode>

Page 15: PHP APIs - Leanpub

3.1.3 Format XML String

Info [R] [C]

This tutorial shows how to use XML_Beautifier to format XML String.

To see how to set formatting options see Format XML String – With Options.

test.php

<?php

//ADD PATH TO PEAR TO php.ini PARAMETER include_path.

set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/share/php');

//INCLUDE BAUTIFIER.

require_once "/usr/share/php/XML/Beautifier.php";

//SETUP XML_Beautifier.

$XMLBeautifier = new XML_Beautifier();

//FORMAT XML.

$xml = '<rootNode><foo bar = "pear">hello world!</foo></rootNode>';

$formatedXML = $XMLBeautifier->formatString($xml);

echo $formatedXML;

?>

output

<rootNode>

<foo bar="pear">hello world!</foo>

</rootNode>

Page 16: PHP APIs - Leanpub

3.1.4 Format XML String with Options

Info [R] [C]

This tutorial shows how to use XML_Beautifier to format XML String by settings additional formatting options.

Options can be set when XML_Beautifier object is created or later using setOptions() function.

test.php

<?php

//DEFINE XML.

$xml = '<rootNode><foo bar = "pear">hello world!</foo></rootNode>';

//ADD PATH TO PEAR TO php.ini PARAMETER include_path.

set_include_path(get_include_path() . PATH_SEPARATOR . '/usr/share/php');

//INCLUDE BAUTIFIER.

require_once "/usr/share/php/XML/Beautifier.php";

//SETUP XML_Beautifier.

$options = array(

"indent" => " ",

"caseFolding" => true,

"caseFoldingTo" => "uppercase",

"normalizeComments" => true

);

$XMLBeautifier = new XML_Beautifier($options);

//FORMAT XML.

$formatedXML = $XMLBeautifier->formatString($xml);

//CHANGE FORMATING.

$XMLBeautifier->setOptions($options);

$XMLBeautifier->setOption("indent", "\t");

$formatedXML = $XMLBeautifier->formatString($xml);

//DISPLAY XML.

echo $formatedXML;

?>

output

<ROOTNODE>

<FOO BAR="pear">hello world!</FOO>

</ROOTNODE>

Page 17: PHP APIs - Leanpub

Options

Option Possible values Default Description

removeLineBreaks TRUE or FALSE TRUE Sets, whether linebreaks should be stripped from cdata

sections

indent any string " " (4 spaces) The string passed to this option will be used to indent the

tags in one level.

linebreak any string "\n" The string passed to this option will be used for linebreaks

You should use "\n" or "\r\n".

caseFolding TRUE orFALSE FALSE Disable or enable case folding for tags and attributes

caseFoldingTo "uppercase" or

"lowercase"

"uppercase" Can be used, if caseFolding is set to TRUE to define whether

tags and attributes should be converted to upper- or

lowercase

normalizeComments FALSE orTRUE FALSE If set to true, all adjacent whitespaces in an XML comment

will be converted to one space. This will convert comments

with more than one line to a comment with one line.

maxCommentLine integer -1 Maximum length of comment line. If a comment exceeds

this limit, it will be wrapped automatically. If set to -1 the

line length is unlimited.

multilineTags TRUE orFALSE FALSE If set to true, a linebreak will be added inside the tags after

each attribute and attributes will be indented.

Page 18: PHP APIs - Leanpub

4 Errors

Info

Following chapters describe different errors that might occur while working with PHP.

Page 19: PHP APIs - Leanpub

4.1 ReadBeanPHP

Info

Following chapters show how to solve different errors related to ReadBeanPHP DB API.

4.1.1 Could not connect to database

Error Message

Fatal error: Uncaught exception 'PDOException' with message 'Could not connect to database (postgres).' in

J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php:761

Stack trace:

//0 J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php(885): RedBeanPHP\Driver\RPDO->connect()

//1 J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php(9560): RedBeanPHP\Driver\RPDO->setDebugMode(true,

Object(RedBeanPHP\Logger\RDefault))

//2 J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\Test.php(6): RedBeanPHP\Facade::debug(true)

//3 {main}

thrown in J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php on line 761

PHP Fatal error: Uncaught exception 'PDOException' with message 'Could not connect to database (postgres).' in

J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php:761

Stack trace:

//0 J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php(885): RedBeanPHP\Driver\RPDO->connect()

//1 J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php(9560): RedBeanPHP\Driver\RPDO->setDebugMode(true,

Object(RedBeanPHP\Logger\RDefault))

//2 J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\Test.php(6): RedBeanPHP\Facade::debug(true)

//3 {main}

thrown in J:\Copy\Projects\WORKSPACES\Workspace\PHPProject\rb.php on line 761

Occurrence

This error might occur when trying to connect to some DB.

<?php

include 'rb.php';

error_reporting(E_ALL);

ini_set('display_errors', '1');

R::setup( 'pgsql:host=localhost;dbname=postgres', 'postgres', 'MyPassword' );

R::debug( TRUE );

?>

Reason

Possible reason is that you didn't setup PHP to use connector for DB that is being used.

Solution

Edit php.ini to use connector for DB that is being used.

Update php.ini by uncommenting any of the following lines

extension_dir = "ext"

extension=php_pdo_pgsql.dll

extension=php_pdo_sqlite.dll

Page 20: PHP APIs - Leanpub

4.1.2 Unable to load dynamic library

Error Message

Occurrence

This error might occur when trying to connect to some DB.

<?php

include 'rb.php';

error_reporting(E_ALL);

ini_set('display_errors', '1');

R::setup( 'pgsql:host=localhost;dbname=postgres', 'postgres', 'MyPassword' );

R::debug( TRUE );

?>

Reason

Possible reason is that PHP can't load connector for particular DB because it can't locate it.

Solution

Edit php.ini to be able to proparly locate connectors location.

Update php.ini by uncommenting following line

extension_dir = "ext"