Nov
28
2008
0

Strings and Patterns: Matching

The PHP 5 Zend Certification exam section Strings and Patterns requires knowledge of Matching. It is presumed that matching isto the use of strspan();

You can use strspan(); to match a strings constrictors against allowed (whitelist) constrictors. The function does not reuturn true or false instead returns the amount of constrictors that match the whitelist like so:

$string = ’133445abcdef’;
$mask =12345’;
echo strspn ($string, $mask); // Outputs 6

Their are third and fourth perimeters that can be passed to the function, this sets out the start and end point like such:

$string = ’1abc234’;
$mask = ’abc’;
echo strspn ($string, $mask, 1, 4);

This will output 3, this is because we skip the first character 1 and continue for up to 4 character. Only the first three character meet the mask, so we output 3.

Written by Adam in: 07. Strings and Patterns |
Nov
28
2008
0

Strings and Patterns: Quoting

In the PHP5 Zend Certification has a section under Strings and Patterns called Quoting. The Zend Study Guide does not contain the word Quoting neither does php manual.

Is it referring to Quotation mark, Grave accent and Apostrophe. What do you guys think?

Single Quotes (single quotation mark) are used with simple strings where all characters are used literally.

 echo 'simple string';
echo 'not so simple '.$variable;

Double Quotes escalate complex strings for use with complex characters (such as control characters \x2a) and embedding variables within a string.
Including the use of braces {$variable} within double quotes:

$variable = "variable";
echo "simple string useing double quotes <br>";
echo "double quote useing $variable <br>";
echo "double quote useing multiple {$variable}s <br>";
echo "double quote with \" double quotes \" within it <br>";
echo "double quote with control characters \x2a <br>";
Written by Adam in: 07. Strings and Patterns |
Nov
28
2008
1

REST

Define: Rest

Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. It is not strictly a method for building what are sometimes called “web services.”
The terms “representational state transfer” and “REST” were introduced in 2000 in the doctoral dissertation of Roy Fielding, a principal authors of the Hypertext Transfer Protocol (HTTP) specification. The terms have since come into widespread use in the networking community.

REST strictly refers to a collection of network architecture principles which outline how resources are defined and addressed.
The term is often used in a looser sense to describe any simple interface which transmits domain-specific data over HTTP without an additional messaging layer such as SOAP or session tracking via HTTP cookies. These two meanings can conflict as well as overlap.

Systems such as PHP5 which follow Fielding’s REST principles are often referred to as “RESTful”. Systems that USE REST Feeds are reffered to RESTafarians.

Rest in PHP

REST, is a Web service architectural style in which the focus is on the presence of resources in the system.Each resource must be identified by a global identifier—a URI. To access these resources, clients communicate with the REST service by HTTP, and the server responds with a representation of the resource. This representation is often in the form of HTML or XML.

In simple words, Rest is a way of sending a query to a server. This query can include informatiom such as API Key, User name and Password for secure identification, or a query term such as search=$term to search the website for $terms. The results are returned in either HTML or more prefered XML.

REST needs API

All REST services need an API to allow developers to code the use of a RESTafarian website. This is because REST does not provide a WSDL or hany any common interface for communication.

Working with REST

Most REST requests are responded with XML data this means PHP can use SimpleXML or DOM. In this example we will be using SimpleXML because its more simpler to explain.

In this example we will use delicious.com, which is a bookmark website where you and others bookmark websites with tags to find them later. We can query delicious and ask them for all bookmarks related to the word Zend. Delicious will then respond to us all the websites it has been tagged with Zend:

$u = ’username’;
$p = ’password’;
$query = 'ZEND';
$fooTag = "https://{$u}:{$p}@api.del.icio.us/v1/posts/all?tag={$query}";
$bookmarks = new SimpleXMLElement($fooTag, NULL, true);
foreach ($bookmarks->post as $bookmark){
	echo<a href="’ . htmlentities($bookmark[’href’]) . ’">’;
	echo htmlentities($bookmark[’description’]);
	echo "</a><br />\n";
}

$footag s the resource identifier, for the data to be retrieved.
SimpleXML handles the request and the data received, then we use the SimpleXML object and foreach to output the matching bookmarks.

Written by Adam in: Zend Classification General |
Nov
27
2008
0

PHP5 Soap: Creating Server

As SoapClient makes it easy to interprate Web Service, SoapServer will make it easy to provide Soap Services. To create a SOAP server you simply start with a class that contains methods (functions) that you wish to allow other computers to use.

Creating a Small SOAP Server

class MySoapServer{
	public function getMessage(){
		return ’Hello, World!’;
	}
	public function addNumbers($num1, $num2){
		return $num1 + $num2;
	}
}

The above is a class, this contains the methods that we want to let people use, so we are turning our server into a Hello World Calculator.

SOAP by default does not output in WDSL mode, this is tedious and you have to create your WSDL file manually. Its recommended to use WSDL as it gives your users the methods and data types available. The server prefers WSDL as it makes handling complex data simpler.

In this example we will operate in non-WSDL mode.

In the example bellow we inform SOAP that the class we went it to work with is MySoapServer (shown above):

$options = array(’uri’ => ’http://example.org/soap/server/’); //Define Soap Options
$server = new SoapServer(NULL, $options); //Start soapserver and provide it the options
$server->setClass(’MySoapServer’);//Tell Soap which Class to work with
$server->handle(); //process incoming requests

Useing our new SOAP Server

The followng code shows how a computer can interact with our SOAP server, you will notice how the client is able to access getMessage() and addNumbers():

//Define Options
$options = array(
’location’ => ’http://example.org/soap/server/server.php’,
’uri’ => ’http://example.org/soap/server/’
);
$client = new SoapClient(NULL, $options); //Create SOAP Class and give it Options
echo $client->getMessage() . "\n"; // This will output Hello WOrld
echo $client->addNumbers(3, 5) . "\n"; //This will output 8
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

PHP5 SOAP: Debugging

SoapClent allows us to debug messages sent and received. This is done by setting the trace option to 1 when instantiating SOAP. This gives us the SOAP headers and envelope body.

$client = new SoapClient('http://api.google.com/GoogleSearch.wsdl',array('trace' => 1));
$results = $client->doGoogleSearch(NULL, $query, 0, 10, FALSE, '',FALSE, '', '', '');
echo $client->__getLastRequestHeaders();
echo $client->__getLastRequest();

This will output the header requests of the file, followed by the envelope bodies.

POST /search/beta2 HTTP/1.1
Host: api.google.com
Connection: Keep-Alive
User-Agent: PHP SOAP 0.1
Content-Type: text/xml; charset=utf-8
SOAPAction: "urn:GoogleSearchAction"
Content-Length: 900
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="urn:GoogleSearch"
 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:doGoogleSearch>
<key xsi:type="xsd:string">XXXXXXXXXX</key>
<q xsi:type="xsd:string">PHP: Hypertext Preprocessor</q>
<start xsi:type="xsd:int">0</start>
<maxResults xsi:type="xsd:int">10</maxResults>
<filter xsi:type="xsd:boolean">false</filter>
<restrict xsi:type="xsd:string"></restrict>
<safeSearch xsi:type="xsd:boolean">false</safeSearch>
<lr xsi:type="xsd:string"></lr>
<ie xsi:type="xsd:string"></ie>
<oe xsi:type="xsd:string"></oe>
</ns1:doGoogleSearch>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

PHP5 SOAP

SOAP Trivia: SOAP used to stand for Simple Object Access Protocol, but in SOAP 1.2 t was dropped and now SOAP means SOAP.

About SOAP

SOAP is anouther tool for communication between two systems, allowing you to define and exchange data types in request or responce. It is interlinked to XML as all messages are sent in a SOAP envelope that is an XML wrapper, but creating XML for this wrapper is tedious therefore PHP5 simplifies this process with its SOAP extension making use of Servers and Clients easy.

A SOAP Web service is defined by using a Web Service Description Language (WSDL, pronounced “whisdl”) document. This, in turn, is yet another XML document that describes the function calls made available by a Web service, as well as any specialized data types needed by it.

SOAP also supports Remote Procedure Call (RPC). this allows you to execute a procedure on another address space (a different local computer). RPC may be referred to as remote invocation or remote method invocation.

Using SOAP Web Services

As we mentioned SOAP is used for communication between two computers, in the example bellow we will talk to google. SoapClient gives us such ability, the first step is to tell SOAP the path to a WSDL fle.

<?php
try{
	$client = new SoapClient('http://api.google.com/GoogleSearch.wsdl');
	$results = $client->doGoogleSearch($key, $query, 0, 10, FALSE, '',FALSE, '', '', '');
	foreach ($results->resultElements as $result){
		echo '<a href="'.htmlentities($result->URL).'">';
		echo htmlentities($result->title, ENT_COMPAT, 'UTF-8');
//		echo htmlentities($result->title);
		echo '</a><br/>';
	}
}
 
catch (SoapFault $e){
	echo $e->getMessage();
}
?>

This creates a new SOAP client using Google’s WSDL file. SoapClient uses theWSDL file to construct an object mapped to the methods defined by the web service; thus, $client will now provide the methods doGetCachedPage(), doSpellingSuggestion(), and doGoogleSearch(). In our example, the script invokes the doGoogleSearch() method to return a list of search results. If SoapClient encounters any problems, it will throw an exception, which we can trap as explained in the Object-oriented Programming in PHP chapter). The constructor of the SOAPClient class also accepts, as an optional second parameter, an array of options that can alter its behaviour; for example, you can change the way data is encoded, or whether the entire SOAP exchange is to be compressed, and so on.

Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

Web Services

Define: Web Services

provide a standard means of interoperating between different software applications, running on a variety of platforms and/or frameworks
- Quote W3C

In other words Web Services is a term for allowing programming language A on one system, to pass data effectively to Programming Language Y on a different system.
Today we have three popular types of web services:
- XML-RPC
- SOAP
- REST
As expected PHP 5 contained tools to use with XML it also has 5 tools suited for SOAP and REST.

Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

XML Dom: Use with SimpleXML

You can interchange data with SimpleXML and DOM, this allows us to take advantage of each systems strengths. We can import SimpleXML objects to DOM by using:
dom_import_simplexml();

$sxml = simplexml_load_file(’library.xml’); //Import libary.xml to simplexml
$node = dom_import_simplexml($sxml); //Convert data from SimpleXML to Dom
 
$dom = new DomDocument(); //Create dom Object
$dom->importNode($node, true); //Import simplexml data to Dom
$dom->appendChild($node);

The opporsite is obviosy possible, taking DOM data to SimpleXML:

$dom = new DOMDocument(); // Start DOM object
$dom->load(’library.xml’); // Import XML to Dom
$sxe = simplexml_import_dom($dom); //Import DOM to SimpleXML $sxe
echo $sxe->book[0]->title;//Print out the first books title
Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

XML Dom: Remove Data

XML Dom: Removing Data

Their are three types of data you may want to delete from a XML document:
attributes
elements
CData
PHP5 Dom has different methods for each of these tasks:
DomNode::removeAttribute();
DomNode::removeChild();
DomCharacterData::DeleteData();

//Create String XML Document
$xml = <<<XML
<xml>
<text type="misc">some text here</text>
<text type="misc">some more text here</text>
<text type="misc">yet more text here</text>
</xml>
XML;
 
$dom = new DOMDocument(); //Create DOM Object
$dom->loadXML($xml); //Load XML String to Dom Object
 
$xpath = new DomXpath($dom);//Start xpath
$result = $xpath->query("//text"); //fetch all <text xml dat
 
$result->item(0)->parentNode->removeChild($result->item(0)); // Will remove the whole first set of XML data "some text here"
 
$result->item(1)->removeAttribute(’type’); // Remove type=""
$result = $xpath->query(’text(), $result->item(2));
$result->item(0)->deleteData(0, $result->item(0)->length);
echo $dom->saveXML();

In this example, we start by retrieving all of the text nodes from our document, then we remove the first one by accessing its parent and passing the former to DomNode::removeChild(). Next, we remove the type attribute from the second element using DomNode->removeAttribute(). Finally, using the third element,we use Xpath again to query for the corresponding text() node, passing in the third element as the context argument, and then delete the CDATA using DomCharacterData::deleteData(), passing in an offset of 0 and a count that is the same as the length of the CDATA node.

Written by Adam in: 06. XML and Web Services |
Nov
27
2008
0

XML Dom: Modifying Data

We can modify data using DOM and XPath, in this example bellow we will create a sample XML document and use UCWords to capitalise the first letter of the words in the XML Document.

$xml = <<<XML
<xml>
<text>some text here</text>
</xml>
XML;
$dom = new DOMDocument(); //Create dom Object
$dom->loadXML($xml); // Load XML from string above
$xpath = new DomXpath($dom); // Use xpath with dom
$node = $xpath->query("//text/text()")->item(0); // use xpath to get the data from xml
$node->data = ucwords($node->data); //capitalise the data, then set it back to the variable
echo $dom->saveXML();//Output XML to string

We can change the line ucwords($node->data); to anything allowing us to change the data completely, add a prefix, suffix, uncapitalised whatever you need to do to modify the data.
We can also use a loop, to capitalise all data in the xml document.

Written by Adam in: 06. XML and Web Services |

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS