Free Essay

Php for Social Solutions

In:

Submitted By monksaigon
Words 10232
Pages 41
Object-Oriented Programming with PHP5

Learn to leverage PHP5's OOP features to write manageable applications with ease
Hasin Hayder

BIRMINGHAM - MUMBAI

Object-Oriented Programming with PHP5
Copyright © 2007 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2007

Production Reference: 1031207

Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-847192-56-1 www.packtpub.com Cover Image by Karl Moore (karl.moore@ukonline.co.uk)

Credits
Author Hasin Hayder Reviewers Kalpesh Barot Murshed Ahmed Khan Proofreader Development Editor Nanda Padmanabhan Production Coordinator Assistant Development Editor Rashmi Phadnis Cover Designer Technical Editor Divya Menon Editorial Team leader Mithil Kulkarni Shantanu Zagade Shantanu Zagade Damian Carvill Project Manager Abhijeet Deobhakta Indexer Monica Ajmera

About the Author
Hasin Hayder is a Zend Certified Engineer and open-source enthusiast from
Bangladesh. Besides his regular job as Technical Director at Trippert Labs (www.trippert.com), he is often found developing localized Bangla applications and blogging at http://hasin.wordpress.com. He lives in Bangladesh with his wife Ayesha, son Afif and plenty of toys around!

About the Reviewers
Kalpesh Barot has about 4 years of experience in the world of PHP. He has extensively worked on small and large scale social networking websites developed in PHP. He has been involved in varied projects, from planning and developing web sites to creating custom modules on big social networking websites. Kalpesh received a Masters degree in Enterprise software Engineering from the University of Greenwich, UK in 2004. There he learned the theory behind his computer experience and became a much more efficient computer programmer. Kalpesh has worked actively in the IT sector since his freshman year at university. He has been a PHP developer since then and has developed his skills in this field. Through his increasing responsibilities, he has learned to prioritize needs and wants, and applies this ability to his projects. I would like to thank my wife Bansari for her consistent support.

Murshed Ahmmad Khan is a young web developer who believes that nothing is impossible in the arena of programming. With his extensive 5 years work experience in web & system level programming he wants to create cool, applicable and useful systems for many people throughout the web. He graduated (B.Sc. in CSE) from Rajshahi University of Engineering & Technology (RUET) Rajshahi, Bangladesh, in Computer Science & Engineering (CSE). Murshed Ahmmad Khan worked on BangladeshInfo.com (http://www.bangladeshinfo.com), and Global Online Services Limited (http://www.global.com.bd) gaining an immense reputation. BangladeshInfo.com & Global Online Services Limited are both a concern of Texas Group Bangladesh and a renowned IT firm in the local market for corporate and multinational companies. He also worked in THPB (The Hunger Project, Bangladesh http://www.thp.org) and SHUJAN (SHUJAN is a citizen movements to achieve good governance) as a lead developer for developing various e-governance sites for increasing the accountability of the candidates of national elections. From SHUJAN (http://www.shujan.org) he also developed the country's first ever online.

Table of Contents
Introduction Chapter 1: OOP vs. Procedural Programming
Introduction to PHP A Little History of OOP in PHP Procedural vs. OO Coding Style Benefits of OOP Dissection of an Object Difference of OOP in PHP4 and PHP5 Some Basic OO Terms General Coding Conventions Summary 6 6 7 8 9 11 12 13 14

1 5

Chapter 2: Kick-Starting OOP

Let's Bake Some Objects Accessing Properties and Methods from Inside the Class Using an Object Modifiers Constructors and Destructors Class Constants Extending a Class [Inheritance] Overriding Methods Preventing from Overriding Preventing from Extending Polymorphism Interface Abstract Class Static Method and Properties

15

15 17 17 18 20 22 24 26 26 26 27 28 30 32

Table of Contents

Accessor Methods Using Magic Methods to Set/Get Class Properties Magic Methods for Overloading Class Methods Visually Representing a Class Summary

34 36 37 38 39

Chapter 3: More OOP

Class Information Functions Checking if a Class Already Exists Finding Currently Loaded Classes Finding out if Methods and Properties Exists Checking the Type of Class Finding Out the Class Name Exception Handling Collecting all PHP Errors as Exception Iterators ArrayObject Array to Object Accessing Objects in Array Style Serialization Magic Methods in Serialization Object Cloning Autoloading Classes or Classes on Demand Method Chaining Life Cycle of an Object in PHP and Object Caching Summary You Might have Done this Before… Strategy Pattern Factory Pattern Abstract Factory Adapter Pattern Singleton Pattern Iterator Pattern Observer Pattern Proxy Pattern or Lazy Loading Decorator Pattern Active Record Pattern Facade Pattern Summary
[ ii ]

41

41 41 42 42 42 43 44 48 49 51 52 53 54 55 58 59 59 61 62 63 64 66 69 71 75 77 80 82 84 88 88 91

Chapter 4: Design Patterns

63

Table of Contents

Chapter 5: Reflection and Unit Testing
Reflection ReflectionClass ReflectionMethod ReflectionParameter ReflectionProperty Unit Testing Benefits of Unit Testing A small Introduction to Vulnerable Bugs Preparing for Unit Testing Starting Unit Testing Testing an Email Validator Object Unit Testing for Everyday Script Test Driven Development PHPUnit API Summary
Writing Multiple Assertions

93 94 99 102 104 106 107 107 109 109 112 116 120 126 136

93

125

Chapter 6: Standard PHP Library
Available Objects in SPL ArrayObject ArrayIterator DirectoryIterator RecursiveDirectoryIterator RecursiveIteratorIterator AppendIterator FilterIterator LimitIterator NoRewindIterator SeekableIterator RecursiveIterator SPLFileObject SPLFileInfo SPLObjectStorage Summary

137

137 138 143 145 149 150 150 152 154 154 155 156 158 159 161 163

Chapter 7: Database in an OOP Way
Introduction to MySQLi Connecting to MySQL in an OO Way Selecting Data in an OO Way Updating Data in an OO Way

165

165 166 166 167

[ iii ]

Table of Contents

Prepared Statements

Using BLOB with Prepared Statements Executing Stored Procedure with MySQLi and PHP PDO DSN Settings for Different Databases Engines Using Prepared Statements with PDO Calling Stored Procedures Other Interesting Functions Introduction to Data Abstraction Layers ADOdb
Installing ADOdb Connecting to Different Databases Basic Database Operations using ADOdb Inserting, Deleting, and Updating Records Executing Prepared Statements Installing MDB2 Connecting to Database Executing Prepared Statements

Basic Prepared Statements Prepared Statements with Variables

167 170 171 172 174 175 176 177 178 178

168 169

MDB2

185

178 179 183 184 184 185 186 187

Introduction to ActiveRecord Creating a New Record via ActiveRecord Selecting and Updating Data Summary

188 189 189 190

Chapter 8: Cooking XML with OOP

Formation of XML Introduction to SimpleXML Parsing Documents Accessing Attributes Parsing Flickr Feeds using SimpleXML Managing CDATA Sections using SimpleXML XPath DOM API Modifying Existing Documents Other Useful Functions Summary What is MVC? Planning for the Project Designing the Bootstrap File

191

191 192 193 194 194 197 198 200 202 202 203 205 206 206

Chapter 9: Building Better with MVC

205

[ iv ]

Table of Contents

Adding Database Support Drivers Building Applications over our Framework Authentication Controller Summary

224 227 237 238 245

Index

247

[v]

Introduction
Object-oriented programming is largely about the ability to hide what's not important to the user and to highlight what is. PHP 5 offers standardized means for specifying the variety of property scopes typically offered by full-featured OO languages.

What This Book Covers

Chapter 1 introduces object-oriented programming and how it fits for PHP. Some benefits of functional programming over procedural programming are highlighted. In Chapter 2 you learn to create objects and define their properties and methods. Details of classes, properties, and methods follow, along with the scope of methods. This chapter shows you the benefits of using interfaces and a few other basic OOP features in PHP to kick start your journey through OOPing in PHP. Now that you have got your basics done for OOP in PHP, Chapter 3 helps you to strengthen your base. It helps you to deal with more details and some advanced features. For example, you learn about class information functions, which allows you to investigate details of any class. This chapter takes you through some handy object-oriented information functions, exception handling, iterators, and storing objects using serialization. In Chapter 4 you learn some of the Design Patterns and how to implement them in PHP. These are an essential part of OOP and make your code more effective, more efficient, and easier to maintain. Sometimes we implement these design patterns in our code without knowing that these solutions are defined by design patterns. Proper usage of the correct pattern can make your code perform better; similarly using them improperly could make your code slower and less efficient.

Introduction

Chapter 5 focuses on two very important features of object-oriented programming in PHP, reflection and unit testing. PHP5 replaces many old APIs with smarter new ones. One of these is the Reflection API, with which you can reverse or engineer any class or object to figure out its properties and methods. You can invoke those methods dynamically and more. Unit testing is an essential part of good, stable, and manageable application design. We focus on one very popular package, PHPUnit, which is a port of JUnit to PHP. If you follow the guidelines provided in this chapter you will be able to design your own unit tests successfully. Some built-in objects and interfaces in PHP make life much easier for PHP developers. In Chapter 6 you will learn about the huge object repository named the Standard PHP Library or SPL. Chapter 7: In this chapter we discuss the improved MySQL API known as MySQLi and take a basic look at PHP Data Objects (PDO), adoDB, and PEAR::MDB2. We take a look at the Active Record pattern in PHP using adoDB’s active record library and the Object-Relational Mapping (ORM) pattern using Propel. We focus on some specific topics that are interesting for PHP developers doing database access the OO way. In Chapter 8, you learn to process XML with PHP. You get to know about different APIs like the SimpleXML API to read XML and the DOMDocument object to parse and create XML documents. Chapter 9: In Chapter 4 you learned how design patterns can simplify your daily life in programming by providing you with a common approach for solving problems. One of the most used design patterns for application architecture is Model-View-Controller (MVC). In this chapter we discuss the basic structure of MVC frameworks and then introduce you to some of these popular frameworks. Frameworks play a very important role in Rapid Development of PHP applications. You will learn how to build a framework in this chapter, which will also help you to understand object loading, data abstraction layers, and the importance of separation and finally you get a closer look at how applications are done.

Who is This Book for Conventions

From beginners to intermediate users of PHP5

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
[2]

Introduction

There are three styles for code. Code words in text are shown as follows: "In some In cases you may need to investigate which classes are in the current scope. You can do it easily with get_declared_classes() function." ." A block of code will be set as follows:

New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: " If you place the server in your web server (here localhost) document, root in a folder named proxy and then access the client, you will get the following output: March, 28 2007 16:13:20".
Important notes appear in a box like this.

Tips and tricks appear like this.

Reader Feedback

Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply drop an email to feedback@packtpub.com, making sure to mention the book title in the subject of your message.
[3]

Introduction

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the Example Code for the Book
The downloadable files contain instructions on how to use them.

Visit http://www.packtpub.com/files/code/2561_Code.zip, and select this book from the list of titles to download any example code or extra resources for this book. The files available for download will then be displayed.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub. com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata are added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Questions

You can contact us at questions@packtpub.com if you are having a problem with some aspect of the book, and we will do our best to address it.

[4]

This book is dedicated to my Son Afif—The Little Einstein

OOP vs. Procedural Programming
PHP is one of the most popular scripting languages of the last couple of years. Almost 60% of web servers are running on Apache with PHP. It is so popular that millions of websites and web applications are developed every month using PHP. PHP started its journey as a simple replacement for Perl, and in a few years it became tremendously popular and powerful. The language itself is closely similar to ANSI C. One of the reasons why PHP became so popular is its short learning curve. Learning PHP is not a big job, especially if you are familiar with the syntax of Java or C. As writing PHP scripts is easy, anyone can write PHP code without following conventions and mixing presentation layers with business logics (which is one of the main reasons why there are large amounts of unmanageable projects floating around). Because there are no strict coding conventions followed in PHP, over the years as a project gets bigger, it can turn into an unmanageable demon. OOP or Object Oriented Programming is a good programming practise to create manageable projects more easily. Procedural programming means writing code without objects. Procedural programming consists of codes with or without routines. OOP enlightens any language for better coding, for best performance and for writing very big projects without worrying a lot about managing them. OOP gives you facilities to create reusable objects that you or other developers can use in their projects without reinventing them again and again. OOP removes the hassles and difficulties of writing and managing big applications. In this book we are going to discuss how you can achieve maximum benefits using OOP with PHP, using step-by-step instructions, real life examples how OOP helps you to write effective code, how to improve your coding style, and how to reuse them over time. This book won't work as a reference for PHP language; we will just cover OOP features of PHP and not the basics of general PHP. If you are looking for a good reference book, consult the PHP manual at first and then you can study Core PHP Programming, a very good book written by Leon Atkinson. .

OOP vs. Procedural Programming

Introduction to PHP

This section is not for you if you are already a PHP developer, but for those who are new to PHP and starting with this book. Though I said at the very beginning that I assume you will have some pre development experience in PHP while reading this book, but if you are a total fresher and want to learn OOP with this book, this section may be worth recalling the basic PHP language features. If you are already familiar enough, don't skip this section as we have other topics to discuss here. So you may ask where is the introduction to PHP, I am not seeing any code here! Well, you don't need to. The best resource on the internet is for free. Please go to http://www.php.net and download the manual and read the basic chapters. For a detailed learning of PHP, you can study the book Learning PHP5 written by David Sklar.

Ready, Set, Go

In this book, we are using PHP5.1.2 for our examples but for almost 99% of cases it will run with PHP version 5x. We have MySQL 5 in our machine and Apache 2 as our web server. If you aren't familiar with configuring all these in your machine, you can download pre configured WAMP or LAMP distributions like XAMPP (http://apachefriends.org) or Apache2Triad (http://www.apache2triad.net). You will find corresponding documentation for installation and customization on each of these product's website.

A Little History of OOP in PHP

When PHP was developed, it did not implement OO features in itself. After PHP/FI, when Zeev, Rasmus, and Andy rewrote the core and released PHP3, very basic OO features were introduced. When PHP4 was released, OO features got matured with huge performance improvement. But the PHP team rewrote the core engine again to introduce completely new object models and released PHP5. Now there are two versions of PHP being developed. Don't get confused by comparing PHP versions with other languages. PHP5 doesn't mean it is the latest PHP version. As I said a while ago, PHP4 and PHP5 are being released actively (though there will be no more releases of PHP4 after December 2007). Between these two, PHP5 implements almost complete OO features while PHP4 doesn't. At the time of writing this book the latest version of these two streams are PHP5.2 and PHP4.4.

[ 10 ]

Chapter 1

Procedural vs. OO Coding Style

PHP allows you to write code in two flavours, one is procedural and the other is object oriented. You can even write procedural code in PHP5 and it will run without any problems. If you are not clear about procedural and object oriented programming, then we will have a look at these two different coding styles. The following two examples are not fully running examples rather a pseudo code:

You will notice using a lot of inline processing either directly or via using functions. It may stand as an example of typical procedural operation. Let's see how it looks after converting it to OOP:

Now if you take a look into these two code snippets, you will find that the latter one is much more readable. Well, you can make the first one more readable by introducing some more functions into it, but how many functions are you ready to search into when you use them? The latter snippet is better organized because you know which object is handling which process. If you write big applications in procedural style, it will be almost impossible to manage after a few versions. Of course you can implement strict coding conventions, but it is agreed by millions of developers that it won't give you the ultimate manageability and usability if it's procedural unless you do it in OO style. Almost all big applications are written using the object oriented approach.
[ 11 ]

OOP vs. Procedural Programming

Benefits of OOP

OOP is invented to make the developer's life easier. Using OOP you can split your problems into smaller problems that are comparatively easy to comprehend. The main goal of OOP is: everything you want to do, do it via objects. Objects are basically small discrete pieces of code which, can incorporate data and behaviors together. In an application all these objects are connected to each other, they share data among them and solve problems. OOP can be considered better from many aspects, especially when you consider the development time and maintenance overhead. The main benefits of OOP can be considered as follows: • Reusability: An object is an entity which has bundles of properties and methods and can interact with other objects. An object can be sufficient or it may have dependencies over other objects. But an object is usually developed to solve a specific set of problems. So when other developers suffer from the same set of problems, they can just incorporate your class to their project and use it without affecting their existing workflow. It prevents from DRY, which means Don't Repeat Yourself. In functional or modular programming, reusing is possible but complex. Refactoring: When you need to refactor your projects, OOP gives you the maximum benefit because all objects are small entities and contain its properties and methods as a part of itself. So refactoring is comparatively easier. Extensible: If you need to add features to your project, you can achieve best results from OOP. One of the core OOP features is extensibility. You can refactor your object to add the feature. While doing it, you can still maintain backward compatibility of this object so that it works fine with an old code base. Or you can extend the object and create a totally new object that retains all the necessary properties and methods of the parent object from which it has been derived, and then expose new features. This is termed "inheritance" and is a very important feature of OOP. Maintenance: Object oriented code is easier to maintain because it follows somewhat strict coding conventions and is written in a self explanatory format. For example, when a developer extends it, refactors it, or debugs it, they can easily find out the inner coding structure and maintain the code time after time. Moreover, whenever there is a team development environment in your project, OOP could be the best solution because you can distribute your code after splitting it into small parts. These small parts could be developed as a separate object, so developers can develop them almost independently. Finally, it will be very easy to merge the code.
[ 12 ]







Chapter 1



Efficiency: The concept of object oriented programming is actually developed for better efficiency and ease of development process. Several design patterns are developed to create better and efficient code. Moreover in OOP, you can think of your solution in a much better approach than procedural programming. Because you first split your problem into a small set of problems and then find solutions for each of them, the big problem is solved automatically.

Dissection of an Object

So what is an object? Well, it's nothing but a piece of code with a bunch of properties and methods. So is it similar to an array, as arrays can store data identified by properties (well, they are called keys)? Objects are much more than arrays because they contain some methods inside them. They can either hide them or expose them, which are not possible in arrays. The object is somewhat comparable with a data structure, data structure, and can incorporate a lot of other objects in itself and either creates a tight coupling among them or a loose one. And object can incorporate a lot of other object in itself and either creates a tight coupling among them or a loose one. We will learn more about loose coupling and tight coupling later in this book and understand how they will be useful for us. Let's see the code of an object in PHP. The following object is a very simple object which can send email to a bunch of users. In PHP5, objects are a lot more different than an object in PHP4. We will not discuss the details of it, this is just an introductory object to see how the objects are written in PHP.

The above object contains four private properties and three accessor methods and finally one more method to dispose the email to recipients. So how we are going to use it in our PHP code? Let's see below:

I am sure that the above code snippet is much more self explanatory and readable. If you follow proper conventions, you can make your code easy to manage and maintain. Wordpress developers use a motto on their site www.wordpress.org which is "Coding is poetry". Coding is exactly a poem; if you just know how to write it.

[ 14 ]

Chapter 1

Difference of OOP in PHP4 and PHP5

Objects in PHP5 differ a lot from objects in PHP4. OOP became matured enough in true sense from PHP5. OOP was introduced since PHP3 but that was just an illusion for real object oriented programming. In PHP4 you can create objects but you can't feel the real flavour of an object there. In PHP4 it was almost a poor object model. One of the main differences of OOP in PHP4 is that everything is open; no restrictions about the usage of methods or properties. You can't use public, private, and protected modifiers for your methods. In PHP4 developers usually declare private methods with a double underscore. But it doesn't mean that declaring a method in that format actually prevents you from accessing that method outside the class. It's just a discipline followed. In PHP4 you can find interfaces but no abstract or final keyword. An interface is a piece of code that any object can implement and that means the object must have all the methods declared in the interface. It strictly checks that you must implement all the functions in it. In the interface you can only declare the name and the access type of any method. An abstract class is where some methods may have some body too. Then any object can extend that abstract class and extend all these methods defined in that abstract class. A final class is an object which you are not allowed to extend. In PHP5 you can use all of these. In PHP4 there are no multiple inheritances for interfaces. That means an interface can extend only one interface. But in PHP5 multiple inheritance is supported via implementing multiple interfaces together. In PHP4, almost everything is static. That means if you declare any method in the class, you can call it directly without creating an instance of it. For example the following piece of code is valid in PHP4: [ 15 ]

OOP vs. Procedural Programming

However it is not valid in PHP5 because the method echosomething() uses $this keyword which is not available in a static call. There is no class-based constant in PHP4. There is no static property in objects in PHP4, and there is no destructor in PHP4 objects. Whenever an object is copied, it is a shallow copy of that object. But in PHP5 shallow copy is possible only using the clone keyword. There is no exception object in PHP4. But in PHP5 exception management is a great added feature. There were some functions to investigate methods and properties of a class in PHP4, but in PHP5 beside those functions, a powerful set of API (Reflection API) is introduced for this purpose. Method overloading via magic methods like __get() and __set() are available in PHP5. There are also lots of built-in objects to make your life easier. But most of all, there is a huge performance improvement in PHP5 for OOP.

Some Basic OO Terms

Some of the basic object-oriented terms are as follows: Class: A class is a template for an object. A class contains the code which defines how an object will behave and interact either with each other, or with it. Every time you create an object in PHP, you are actually developing the class. So sometimes in this book we will name an object as class, as they are both synonymous. Property: A property is a container inside the class which can retain some information. Unlike other languages, PHP doesn't check the type of property variable. A property could be accessible only in class itself, by its subclass, or by everyone. In essence, a property is a variable which is declared inside the class itself, but not inside any function in that class. Method: Methods are functions inside a class. Like properties, methods can also be accessible by those three types of users. Encapsulation: Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The wrapping up of data and methods into a single unit (called class) is known as encapsulation. The benefit of encapsulating is that it performs the task inside without . making you worry.

[ 16 ]

Chapter 1

Polymorphism: Objects could be of any type. A discrete object can have discrete properties and methods which work separately to other objects. However a set of objects could be derived from a parent object and retain some properties of the parent class. This process is called polymorphism. An object could be morphed into several other objects retaining some of its behaviour. Inheritance: The key process of deriving a new object by extending another object is called inheritance. When you inherit an object from another object, the subclass (which inherits) derives all the properties and methods of the superclass (which is inherited). A subclass can then process each method of superclass anyway (which is called overriding). Coupling: Coupling is the behaviour of how classes are dependent on each other. Loosely coupled architecture is much more reusable than tightly coupled objects. In the next chapter we will learn details about coupling. Coupling is a very important concern for designing better objects. Design Patterns: First invented by the "Gang of Four", design patterns are just tricks in object oriented programming to solve similar sets of problems with a smarter approach. Using design patterns (DP) can increase the performance of your whole application with minimal code written by developers. Sometimes it is not possible to design optimized solutions without using DP. But unnecessary and unplanned use of DP can also degrade the performance of your application. We have a chapter devoted for design patterns in this book. Subclass: A very common term in OOP, and we use this term throughout this book. When an object is derived from another object, the derived one is called the subclass of which it is derived from. Superclass: A class is superclass to an object if that object is derived from it. To keep it simple, when you extend an object, the object which you are extending is the superclass of a newly extended object. Instance: Whenever you create an object by calling its constructor, it will be called an instance. To simplify this, whenever you write some thing like this $var = new Object(); you actually create an instance of object class.

General Coding Conventions

We will be following some conventions in our codes throughout the book. Not being too strict, these conventions will help you to maintain your application at a large extent. Also, it will increase the maintainability of your code. It will also help you to write efficient code by avoiding duplicity and redundant objects. Last but not least, it will make your code much more readable.
[ 17 ]

OOP vs. Procedural Programming

• •

In a single php file, we never write more than one class at a time. Out of the scope of that class, we will not write any procedural code. We will save any class with a proper naming convention. For example we will save the file where we place the Emailer class introduced earlier in this chapter as class.emailer.php. What benefits can you achieve using this naming convention? Well, without going inside that file, you are now at least confirmed that this file contains a class named "Emailer". Never mix the case in filenames. It creates ugly application structure. Go ahead with all small letters. Like classes, we will save any interface as interface.name.php, Abstract class as abstract.name.php, and Final class as final.name.php. We will always use Camel case while naming our classes. And that means the first letters of the major part is always a capital letter and the rest are small letter. For example a class named "arrayobject" will be more readable if we write ArrayObject. While writing the name of properties or class variables, we will follow the same convention. While writing the name of a method, we will start with a small letter and then the rest are camel case. For example, a method to send an email could be named as sendEmail. Well, there is no more conventions used in this book.

• • •

• •



Summary

In this chapter we learned about the object oriented programming and how it fits in with PHP. We have also learned some benefits over procedural and functional programming. However, we haven't gone through the details of OO language in PHP. In the next chapter we will learn more about objects and their methods and attributes, specifically creating objects, extending its features, and interacting between them. So, let our journey begin, Happy OOPing with PHP.

[ 18 ]

Kick-Starting OOP
In this chapter we will learn how to create objects, define their attributes (or properties) and methods. Objects in PHP are always created using a "class" keyword. In this chapter we will learn the details of classes, properties, and methods. We will also learn the scope of methods and about modifiers and the benefits of using interfaces This chapter will also introduce us to other basic OOP features in PHP. As a whole, this chapter is one of the better resources for you to kick-start OOP in PHP.

Let's Bake Some Objects

As I said before, you can create an object in PHP using the class keyword. A class consists of some properties and methods, either public or private. Let's take the Emailer class that we have seen in our first chapter. We will discuss here what it actually does:

In this code, we started with class Emailer, which means that the name of our class is Emailer. While naming a class, follow the same naming convention as variables, i.e. you can't start with a numeric letter, etc. After that we declared the properties of this class. There are four properties here, namely, $sender, $recipient, $subject, and $body. Please note that we declare each of them with a keyword private. A private property means that this property can only be accessed internally from this class. Properties are nothing but variables inside a class. If you remember what a method is, it is just a function inside the class. In this class there are five functions, __construct(), addRecipient(), setSubject(), setBody(), and sendEmail(). Please note that the last four methods are declared public. That means when someone instantiates this object, they can access these methods. The __construct() is a special method inside a class which is called constructor method. Whenever a new object is created from this class, this method will execute automatically. So if we have to perform some preliminary tasks in our object while initiating it, we will do from this constructor method. For example, in the constructor method of this Emailer class we just set the $recipients as a blank array and we also set the sender name.
[ 20 ]

Chapter 2

Accessing Properties and Methods from Inside the Class public function setBody($body) { $this->body = $body; }

Are you wondering how a function can access the class properties from inside its content? Let's see using the following code:

There is a private property named $body inside our class, and if we want to access it from within the function, we must refer to it with $this. $this means a reference to current instance of this object. So we can access the body property with $this->body. Please note that we have to access the properties (i.e class variables) of a class using a "->" following the instance. Similarly, like properties, we can access any member method from inside another member method in this format. For example, we can evoke setSubject method as $this->setSubject().
Please note that $this keyword is only valid inside the scope of a method, as long as it is not declared as static. You can not use $this keyword from outside the class. We will learn about this "static", "private", "public" keywords more in the Modifiers section later this chapter.

Using an Object

Let's use the newly created Emailer object from inside our PHP code. We must note some things before using an object. You must initiate an object before using it. After initiating, you can access all its public properties and methods using "->" after the ->" instance. Let's see using the following code:

[ 21 ]

Kick-Starting OOP

In the above code piece, we first created an instance of Emailer class to a variable name $emailerobject in the first line. Here, there is something important to note: We are supplying a sender address while instantiating this:
$emailerobject = new Emailer("hasin@pageflakes.com");

Remember we had a constructor method in our class as __construct($sender). When initiating an object, we said that the constructor method is called automatically. So while initiating this Emailer class we must supply the proper arguments as declared in the constructor method. For example the following code will create a warning:

When you execute the above code, it shows the warning as follows:
Warning: Missing argument 1 for emailer::__construct(), called in C:\OOP with PHP5\Codes\ch1\class.emailer.php on line 42 and defined in C:\OOP with PHP5\Codes\ch1\class.emailer.php on line 9

See the difference? If your class had no constructor method or a constructor with no arguments, you can instantiate it with the above code.

Modifiers

You have seen that we used some keywords like private or public in our class. So what are these and why do we need to use them? Well, these keywords are called modifier and introduced in PHP5. They were not available in PHP4. These keywords help you to define how these variables and properties will be accessed by the user of this class. Let's see what these modifiers actually do. Private: Properties or methods declared as private are not allowed to be called from outside the class. However any method inside the same class can access them without a problem. In our Emailer class we have all these properties declared as private, so if we execute the following code we will find an error.

[ 22 ]

Chapter 2

The above code upon execution gives a fatal error as shown below:
Fatal error: Cannot access private property emailer::$subject in C:\OOP with PHP5\Codes\ch1\class.emailer.php on line 43

That means you can't access any private property or method from outside the class. Public: Any property or method which is not explicitly declared as private or protected is a public method. You can access a public method from inside or outside the class. Protected: This is another modifier which has a special meaning in OOP. If any property or method is declared as protected, you can only access the method from its subclass. We will learn details about subclass later in this chapter. But to see how a protected method or property actually works, we'll use the following example: To start, let's open class.emailer.php file (the Emailer class) and change the declaration of the $sender variable. Make it as follows: protected $sender

Now create another file name class.extendedemailer.php with the following code:

Now use this object like this:

Notice that we didn't create any instance of DBManager object like $dbmanager = new DBManager(). Rather we directly access one of its methods using the :: operator. So how does this benefit us? Well, we just need a driver object, so no need to create a new DBManager object and commit it to memory as long as our scripts are executing. Static methods usually perform a specific task and finish it. Here are some important things to note. You can't use $this pseudo object inside a static method. As the class is not instantiated, $this doesn't exist inside a static method. You should rather use the self keyword. Let's take a look at the following example. It shows how a static property actually works:

You will see the output is as follows:
Current Current Current Current Current Id Id Id Id Id From From From From From Static Method is 1 Non Static Method is 2 Static Method is 2 Non Static Method is 2 Static Method is 3

Whenever we create a new instance, it affects all the instances as the variable is declared as static. Using this special facility, a special design pattern "Singleton" works perfectly in PHP.
Caution: Using Static Members Static members make object oriented much like old procedural programming; without creating instances, you can directly call any function, like the old days. That's why we use static method with caution. Excessive static methods make no use at all. Unless you have any specific purpose, don't use static members.

Accessor Methods

Accessor methods are simply methods that are solely devoted to get and set the value of any class properties. It's a good practice to access class properties using accessor methods instead of directly setting or getting their value. Though accessor methods are the same as other methods, there are some conventions writing them. There are two types of accessor methods. One is called getter, whose purpose is returning value of any class property. The other is setter that sets a value into a class property. Let's see how to write the getter and setter methods for class properties:

In the above example there are two getter methods and two setter methods. There is a convention in writing accessor methods. A setter method should start with set and the property name with the first character capitalized. A getter method should start with get followed by the variable name with the first letter capitalized. That means if we have a property named email, the getter method should be named as getEmail and the setter method should be named as setEmail. That's it. So you might ask why someone does these extra jobs, when they can easily set these variables as public and leave everything else as is. Aren't all these the same? Well, no. Using accessor methods, you get some extra benefits. You will have full control while setting or retrieving the value of any property. "So what?" You might ask. Let's use a scenario where you need to filter users' input and set into properties. In this case, a setter can help you to filter the input before setting them into work. Does this mean we have to write 100 getter and setter methods if my class contains 100 properties? You ask as good question. PHP is kind enough to relieve you from this boredom. How? Let us see the next section where we discuss using magic methods for setting and getting property values dynamically. Those methods will reduce the stress up to 90%. Don't you believe me? Let's see.

[ 39 ]

Kick-Starting OOP

Using Magic Methods to Set/Get Class Properties

We discussed in the previous section that writing accessor method for a number of properties will be a real nightmare. To avoid that boredom, you can use magic methods. This process is called property overloading. PHP5 introduced some magic methods in classes to reduce the pain of OOP in some cases. Two of those magic methods are introduced to set and get dynamic property values in a class. These two magic methods are named as __get() and __set(). Let us see how to use them:

Now let us see the code in action. Use the class above with the following script:

When you execute the preceding code, PHP recognizes immediately that no property named name or roll exists in the class. Since the named property doesn't exist, the __set() method is called, which then assigns the value to the newly-created property of the class, allowing you to see the following output:
AutoSet name as: Afif AutoSet roll as: 16 [ 40 ]

Chapter 2

Seems quite interesting, huh? Using magic methods you still have full control over setting and retrieving property values in classes. However, you have one limitation if you use magic methods. While using reflection API, you can't investigate class properties (we will discuss about reflection API in a later chapter). Moreover, your class lost the "readability" and "maintainability" quite a lot. Why? See the code of previous Student class and new Student class and you will understand that for yourself.

Magic Methods for Overloading Class Methods

Like overloading, and using the accessor methods, there are magic methods to overload any method call in a class. If you are still not familiar with method overloading, then this is a process of accessing any method that doesn't even exist in the class. Sounds funny, right? Let's take a closer look. There is a magic method, which helps to overload any method call in PHP5 class context. The name of that magic method is __call(). This allows you to provide actions or return values when undefined methods are called on an object. It can be used to simulate method overloading, or even to provide smooth error handling when an undefined method is called on an object. __call takes two arguments: the name of the method and an array of the arguments passed to the undefined method. For example see the code below:

[ 41 ]

Kick-Starting OOP

If you see the code above, then you will see that there is no method called access and notAnyMethod. So therefore, it should raise an error, right? However, the method overloader still helps you to call any non existing method. If you execute the code above, you will get the following output.
�ou called Array ( [0] => [1] => [2] => ) a method named access with the following arguments

2 3 4

�ou called a method named notAnyMethod with the following arguments Array ( [0] => boo )

That means you will get all arguments as an array. There are many more magic methods, which you will learn step-by-step in this book.

Visually Representing a Class class Emailer _construct($sender) addRecipients($resc) setSubject($subject) setBody($body) sendEmail() $sender $recipient $subject $body

In OOP, sometimes you have to visually represent your class. Let's learn how to visually represent a class. For this, we will use our Emailer class this time.

In this graphical representation, there are three sections. At the top most section a class name should be written. In the second section all methods with or without parameters are written. And in the third box all the properties are written. That's it!

[ 42 ]

Chapter 2

Summary

In this chapter we have learned how to create objects and interact between them. PHP5 brings amazing improvements in object models when compared to PHP4. Zend Engine 2, which is at the core of PHP5, is also very efficient in handling these features with great performance optimization. In the next chapter we will go through more details and the core features of OOP in PHP. But before starting next chapter, please practice everything discussed here, otherwise you may get confused in some topics. Practice them as much as you can, try to refactor all your previous code in OOP. The more you practice, the more efficient you become.

[ 43 ]

More OOP
The previous chapter creates a basis for us to kick-start OOP with PHP. This chapter will deal with some advanced features in more detail. For example, we will learn about class information functions by which we can investigate details about any class. We will then learn about some handy object-oriented information functions and also one of the great new features in PHP5, which is exception handling. This chapter will also introduce us to the Iterators for easier array access. To store any object for later use, we need to use a special feature in OOP which is called serialization, we will also learn about this here. As a whole this chapter will strengthen your base in OOP.

Class Information Functions

If you want to investigate and gather more information regarding any class, these functions will be your light in the dark. These functions can retrieve almost any information regarding a class. But there is an improved version of these functions and is introduced as a totally new set of API in PHP5. That API is called reflection. We will learn about reflection API in Chapter 5.

Checking if a Class Already Exists
".$entry->title.""; echo $entry->content.""; } ?>

This will create the following output. See, how easy SimpleXML is? The output of the above script is shown below:

[ 200 ]

Chapter 8

Managing CDATA Sections using SimpleXML

As we said before, some symbols can't appear directly as a value of any node unless you enclose them using CDATA tag. For example, take a look at following example:

This will generate the following error: Warning: simplexml_load_string() [ function.simplexml-load-string]: Entity: line 2: parser error : xmlParseEntityRef: no name in C:\OOP with PHP5\Codes\ch8\cdata.php on line 10 Warning: simplexml_load_string() [ function.simplexml-load-string]: <content>text & images </content> in C:\OOP with PHP5\Codes\ch8\cdata.php on line 10 Warning: simplexml_load_string() [ function.simplexml-load-string]: ^ in C:\OOP with PHP5\Codes\ch8\cdata.php on line 10

To avoid this problem we have to enclose using a CDATA tag. Let's rewrite it like this:

[ 201 ]

Cooking XML with OOP

Now it will work perfectly. And you don't have to do any extra work for managing this CDATA section. content;//print "text & images" ?>

However, prior to PHP5.1, you had to load this section as shown below:
$s = simplexml_load_string($str,null,LIBXML_NOCDATA);

XPath

Another nice addition in SimpleXML is that you can query using XPath. So what is XPath? It's an expression language that helps you to locate specific nodes using formatted input. In this section we will learn how to locate a specific part of our XML documents using SimpleXML and Xpath. Let's have a look at the following XML: pm cto cto

[ 202 ]

Chapter 8

This document simply states the workflow of an analysis task and then tells it what to do at which state. So now you want to search what to do when the task type is analysis and assigned to cto and current state is new. SimpleXML makes it really easy. Let's take a look at the following code: xpath("//task[@type='analysis']/state[@name='new'] /assigned[@to='cto']"); echo $node[0]->action[0]['newstate']."\n"; echo $node[0]->action[0]->notify[0]; ?>

This will echo the following: clarify pm

[ 203 ]

Cooking XML with OOP

However there is something to remember while writing XPath. When your XPath is followed by / then it means that you should keep the exact sequence of your XML document. For example: echo count($s->xpath("//state"));

This will output 2.
//state means take the state node from anywhere in the document. Now if you specify task//state, it will return all states from under all tasks. For example the following code will output 3 and 3: echo count($s->xpath("//notify")); echo count($s->xpath("task//notify"));

Now what if you want to find notify just under state, following assigned, following action? Your XPath query should be //state/assigned/action/notify. But if you want that, it should be exactly under the task node which is just under the root node, it should be /task/state/assigned/action/notify. If you need to match any attribute then match it as [@AttributeName1='value'] [@ AttributeName2='value']. If you see the following XPath, it will be clear to you:
//task[@type='analysis']/state[@name='new']/assigned[@to='cto']

DOM API

SimpleXML in PHP is used to parse the document however it cannot create any XML document. For creating XML documents on the fly you have to use DOM API that comes bundled with PHP 5. Using DOM API you can also create page-scrapping tools fairly easily. In this section we will learn how to create XML documents using DOM API, and then we will learn how to parse existing documents and modify them. In the following example we will create just a basic HTML file: [ 204 ]

Chapter 8

This will produce the following code: OOP with PHP

That's fairly easy, right? Let's do some more:

This will produce the following code. OOP with PHP Hi - how about some text?

So you can save this XML generated by the DOM engine using the following code entered into a file in your file system: file_put_contents("c:/abc.xml", $doc->saveHTML());

[ 205 ]

Cooking XML with OOP

Modifying Existing Documents

DOM API helps to create XML document easily as well as provide easy access to load and modify existing documents. With the following XML we will load the file we just created a few minutes ago and then we will change the header test of the first h1 object: loadHTMLFile($uri);// load the content of this URL as HTML $h1s = $document->getElementsByTagName("h1");//find all h1 elements $newText = $document->createElement("h1","New Heading");//created a //new h1 element $h1s->item(0)->parentNode->insertBefore($newText, $h1s->item(0));//insert before the existing h1 element $h1s->item(0)->parentNode->removeChild($h1s->item(1));//remove the //old h1 element echo $document->saveHTML();//display the content as HTML ?>

The output is shown below: New Heading Hi - how about some text?

Other Useful Functions
• • • •

There are some other useful functions in the DOM library. We are not going to discuss them in depth, however they are included in this section for a one line overview.
DomNode->setAttribute(): Helps to set the attribute of any node DomNode->hasChildNodes(): Returns true if a DOM node has a child node DomNode->replaceChild(): Replaces any child node with another one DomNode->cloneNode(): Creates a deep copy of the current code

[ 206 ]

Chapter 8

Summary

XML API in PHP5 plays a very important role in web application development, most notably the new SimpleXML API, which simplifies parsing with ease. Today XML is one of the most used data formats for almost all big applications. Therefore getting familiar with XML APIs and relevant technologies will definitely help you to design robust XML-based applications more easily. In the next chapter we will learn about MVC architecture and build a slick MVC framework on our own.

[ 207 ]

Building Better with MVC
In chapter 4 we learned how design patterns can simplify your daily programming life by providing you with common approaches for solving problems. One of the popular design patterns used for application architecture is Model-View-Controller, which is also known as MVC. In RAD (Rapid Application Development) for PHP, MVC frameworks play a vital role. These days several MVC frameworks have gained public interest and many of them are enterprise-ready. For example, symfony framework has been used in developing Yahoo bookmarks, CakePHP is being developed in refactoring Mambo, CodeIgniter is used by many big applications showcased on their site. Also there are popular MVC frameworks like Zend Framework, which is used by IBM and also used to develop the Magento open-source ecommerce solution. Therefore, nowadays, writing code from scratch and fine tuning it is obsolete, and if you are doing this, you should really avoid it. In this chapter, we will discuss the basic structure of MVC frameworks and then introduce you to some of these popular frameworks.

What is MVC?

As the name implies, MVC consists of three components. The first one is Model, the second one is View, and the third one is Controller. This doesn't make any sense if we just list the names. To begin with, Model is an object, which interacts with a database. All business logics are usually written inside the model. A controller is a piece of code, which takes user inputs and based on that initializes models and other objects, and finally invokes all of them. Finally, the View is a component, which displays the result generated by controller with the help of model. So for good practice, you should never implement any business logic in view or controller. Similarly, you should never process the output results in a model. And you should never produce any output directly from controller (instead use the view).

Building Better with MVC

In the following sections we will be creating a very small MVC.

Planning for the Project

For successfully developing any application you must have a clear target. Whenever the architecture of an application is robust, stable, and foolproof, you will get a huge number of users using your application. The MVC framework we are going to develop in this chapter will serve the following issues successfully: • • • • • • • • • • • Small footprint Easy loading of components, libraries, helpers, and models Nice and flexible syntax for developing view Excellent support with popular database servers Will not be resource extensive Easy to use Easy to integrate with other component frameworks like Pear, ezComponents, and so on. Support for caching Layout support like RubyOnRails for easy design of your web application A native gzip compressor for JavaScript Ajax support

Designing the Bootstrap File

The bootstrap is a file, which just prepares the environment for successful execution and integration of controllers, models, and views. Basically a bootstrap file initializes the environment, the router, the object loader, and passes all the input parameters to the controller. We will design the bootstrap file, which will receive all the parameters of a successful request URL with the help of mod_rewrite. mod_rewrite is an apache module, which helps to redirect a request defined by a pattern (regular expression) to another request URL. It is an essential module for almost every web application designed. If you are interested in studying more on it, you can go to: http://httpd. apache.org/docs/2.0/mod/mod_rewrite.html

[ 210 ]

Chapter 9

To enable mod_rewrite you can follow the following details. Firstly, open httpd. conf and add the following lines:
LoadModule rewrite_module modules/mod_rewrite.so Options FollowSymLinks AllowOverride None Order deny,allow Deny from all Satisfy all

We have to place the following code in an .htaccess file and place it inside our application root.
RewriteEngine on RewriteCond $1 !^(index\.php|images|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?$1

This code will just redirect every request to index.php, which will be our bootstrap file. This bootstrap file will receive any requested URL and then split it into different parts like controller, action and parameters. For example, the format will be http://our_application/controller/action/param/param..../param. The bootstrap will analyze the URL with the help of a router and then with the help of dispatcher it will invoke controller and action with all the parameters. Here is the code of our bootstrap file (index.php):

In the above code you see that there is an object called loader. The main purpose of this is to load objects for us, but via the Singleton pattern. This will help us to minimize the load. Using this loader we will load an object named router. There is also an object called dispatcher, which will finally dispatch the web request with the help of router.

[ 211 ]

Building Better with MVC

Let's check the code of core/ini.php, which is a helper to help easy inclusion of class files from different directories.

Here goes the initializer file (core/main/initializer.php):

If you take a look at the code of the initializer file, you will find that it actually just extends the include path. Here is the code of our loader file (core/main/loader.php), which will load different components via the Singleton pattern.

Similar Documents

Premium Essay

Notes

...I. OVERVIEW/ INTRODUCTION As a tropical country, the Philippines has untapped vast potential of solar energy; yet in 1980’s, solar application is beyond the bound of possible solutions in rural, remote areas in the country. Thus in February 27, 1981, Federal Republic of Germany and Republic of the Philippines entered into a contract to develop applications of solar energy in the Philippines. This project was called the Philippine German Solar Energy Project (PGSEP) which was funded by the German Bundesministeruim for Zussamenarbeit through the Gesselchaft for Zussamenarbeit, and Philippine Office Energy. The governing body of the said project was the Philippine National Oil Corporation through its Energy Research and Development Center. Solar power systems is done through the encapsulation of the solar energy from the sun through the photovoltaic (PV) panels which produce direct current (DC) power to run a DC appliance. Additionally, DC current can be converted alternating current (AC) to run AC appliances. The project was anticipated to solve the inexistence of electrical power resources to provide for the basic needs that immediately improve the lives of Filipinos in areas where electricity is not readily available. II. TIME FRAME The proponents point for analysis would be on 1988. This is based on the data given concerning the commencement of PGSEP (Philippine-German Solar Energy Project) on February 27, 1981 to develop a solar source of energy in the Philippines...

Words: 2885 - Pages: 12

Free Essay

Marketing Plan

...285 pounds user weight, and 5” to 6.4” approximately user height and approximately 120 to 165 degrees from floor level continuos motion. The TheraPro relaxation chair have 3 levels of kneading speed, 3 levels of tapping speed, 3 levels of roller width, one full cycle of up/down speed and back stroke range. The accessories will be power cord, T-shaped wrench, thin and thick buffer pad, child safety lock keys, device holder and remote control. The TheraPro relaxation chair covers more area, 1200 square inches. And has 16 pre-programmed massage sessions available. Klismos will target working professionals and athletes who experience physical, mental and emotional. Klismos will both aim for male and female professional whose income ranges from Php 80 000.00 to 120 000.00 and athletes who want to spare from visiting their massage therapist. And believe they all have the capacity to buy the product which very essential to their needs...

Words: 8884 - Pages: 36

Premium Essay

Industrial Tour Report

...the curriculum requirement of BBA program of University of Chittagong .The topic of our report is “Formulating Industrial Marketing Strategies a case study based on PHP Spinning Mils Ltd.”. The PHP Group is a pioneer and acknowledged market leader in spinning sector in Bangladesh and one of the largest spinning manufacturing company of Bangladesh, adopting State-of-the-Art technologies and fulfilling its customers’ requirements through world-class services & products. PHP GROUP Company, PHP Spinning Mills Ltd. has started its production of high quality cotton & melange from January 2006 using latest technology and having production capacity of 466,746 kg per month in which 265,986 kg is cotton & 200,761 kg is melange. The report has been Prepared under direct supervision of Mr. Mohammed Shahedul quader , Assistant Professor , Department of Marketing Studies & international marketing, university of Chittagong. Objectives of the study: The basic or main purpose of industrial tour report is to learn practical knowledge about business world for balancing the gap of our industrial policy in the modern job market. The objectives of this industrial tour are as below: • The prime objective of the study is to know the practical marketing scenario of the company. • To identify an overview of PHP Spinning Mills Ltd. • To perform the SWOT analysis of the company. • To evaluate the performance of the company and generate some policy implication for...

Words: 7104 - Pages: 29

Free Essay

Hmrc Confirms Reporting Obligations for Recruiters

...“Manager” and (“asses” or “Assessor” or “assessment”) and (“refer” or “referral” or “referring”) and (“Learning disabilities” or “LD” or “mental health” or “learning disability”) and (NVQ4 or “NVQ 4” or “NVQ level 4” or “NVQ IV” or NVQ3 or “NVQ 3” or “NVQ level 3” or “NVQ III” or QCF4 or “QCF 4” or “QCF level 4” or “QCF IV” or QCF3 or “QCF 3” or “QCF level 3” or “QCF III” or “Registered manager award” or RMA) and (care or “social care” or “health care” or “home care” or “care home” or “residential care”) (“referral manager” or “assessment manager” or “referral and assessment manager” or “referral and assessment manager”) and (“Learning disabilities” or “LD” or “mental health” or “learning disability”) and (NVQ4 or “NVQ 4” or “NVQ level 4” or “NVQ IV” or NVQ3 or “NVQ 3” or “NVQ level 3” or “NVQ III” or QCF4 or “QCF 4” or “QCF level 4” or “QCF IV” or QCF3 or “QCF 3” or “QCF level 3” or “QCF III” or “Registered manager award” or RMA) (“care manager” or “home manager” or “registered manager” or “branch manager” or “home care manager” or “service manager” or “domiciliary manager” or “dom manager”) and (domiciliary or “dom care” or “homecare” or “home care” or “care agency” or “community care”) and (NVQ4 or “NVQ 4” or “NVQ level 4” or “NVQ IV” or NVQ5 or “NVQ 5” or “NVQ level 5” or “NVQ V” or QCF4 or “QCF 4” or “QCF level 4” or “QCF IV” or QCF5 or “QCF 5” or “QCF level 5” or “QCF V” or “Registered manager award” or RMA) (“live in carer” or “live in manager” or “live-in manager”...

Words: 2489 - Pages: 10

Premium Essay

Marketing

...Forecasting A. Environmental Factors 1. Social Spa goers are becoming more knowledgeable, they are also getting choosier and tend to have higher expectation on their spa experience. Filipinos in urban areas are stressed due to their long working hours, and the lack of work-life balance. 2. Political Philippines is politically stable and the government is committed to promote healthier lifestyles to the public. 3. Economic Trends Following the growth of the local economy, Filipino people has stronger purchasing power and are more willing to spend on luxury experiences, like spa. 4. Technology To reach the spa goers‘ expectation in a cost effective and green way, latest technologies such as using social media to advertise and the offering of portable spa experiences can be seen as viable solutions. B. Competitive Analysis Customers choose spa services based on proximity to their daily commute, quality and an exceptional experience.   There is not one direct competitor of this nature within the area where we are intending to locate.  After an analysis of the local market, four spa are identified as our closest competitor, including Urban Spa, The Palm Garden Health Spa, Exquisite Spa, Holistic Center for Wellness and Medical Spa, Terra Wellness Spa Competitive Trends: - Going green, all-natural ingredients - With respect to social media, sharing tips and creating blogs about...

Words: 519 - Pages: 3

Free Essay

Project

...UNIVERSITY OF NAIROBI SCHOOL OF COMPUTING AND INFORMATICS ONLINE VEGETABLES MARKET PRICE AND TRENDS SYSTEM SECOND YEAR FINAL PROJECT COURSE CODE: 227 NAME: MUIGUA STEPHEN GITAU ADM NO: P15/54335/2012 SUPERVISOR: ERIC AYIENGA   DECLARATION I, Muigua Stephen Gitau, do declare that this project is my own work, and as per my knowledge, it has not been submitted to any other institution of higher learning. Student’s Name: MUIGUA STEPHEN GITAU Registration No: P15/54335/2012 Signature: _________________________________________________________ Date: _________________________________________________________ This project has been submitted as a partial fulfillment of requirements for the Diploma in Computer Science of the University of Nairobi with my approval as the University Supervisor. Supervisor’s Name: Mr. ERIC AYIENGA Signature: ___________________________________________________________ Date: _______________________________________________________________   ACKNWOLEDGEMENT I thank almighty God; I thank Nairobi University of Kenya in Conjunction with the School of Computing and Informatics for facilities and resources they availed during execution of this project. I take this opportunity to express my sincere appreciation to my supervisor Mr. Ayienga and the entire Faculty of Computer Science for the exemplary guidance, monitoring and constant encouragement throughout the course. Lastly, I thank my parents, for their constant...

Words: 4782 - Pages: 20

Premium Essay

Obligations and Contracts

...PAMANTASAN NG LUNGSOD NG MAYNILA University of the City of Manila College of Business and Management Submitted By: Balicanta, Keith Martin Buen, Kristine Dizon, Dayz Angela Lopera, Joyce Ann Manio, Josie Marie Mateo, Dinecen Shairo Panganiban Chriscelle A. Executive Summary Background Dermstrata is a skin clinic that offers various skin care products and services. It is established by Dr. Winnie Rodriguez in December of 1998 and their first branch is at SM Centerpoint. Product/ Services Wrinkles, oily face, pimples, etc. These are the common problems of many human beings which are experiencing puberty changes. Many of them are willing to pay any amount for them to get rid of these things. Many products arise from market to resolve this kind of problem. Dermstrata is known for high quality of skin care service and product, such as facial soap, aramond peel and others. The new product is facial wash for men and facial treatment. The new products are economically competent and the people in the low and middle class can afford it. The price of the new product are more cheaper than the existing product and this marketing plan offers discount which is called “Barkada Package” that if you buy 5 soap, you can get 1 free. And in service, in the 6th session, you can avail 50% discount off. The new target market of this marketing is to get the attention of males. These marketing plans suggest that using male models for their new promotion. By this, they can get the...

Words: 2706 - Pages: 11

Premium Essay

Subic Bay Ict Profile

...SBFZ ICT PROFILE (For Updating) SUBIC BAY FREEPORT ZONE: ICT HUB LOCATION PROFILE Page 1 SITUATIONAL ANALYSIS (INTERNAL LANDSCAPE) ANALYSIS: CURRENT PRODUCT - SUBIC BAY SPECIAL ECONOMIC AND FREEPORT ZONE Product Features, Benefits, and Appeals Subic Bay Freeport Zone (SBFZ) has a total area of 67, 452 hectares both land and water (water area has a total of 12,350 hectares and a land area of 55, 102 hectares as defined by Proclamation No. 532 of the Subic Special Economic and Freeport Zone SSEFZ) Metes and Bound. It is comprised by the City of Olongapo, Subic Town, San Antonio in Zambales and the former US Naval Reservation. The earliest predecessor to the USFAC Subic Bay was an un finished Spanish Naval Station, acquired by the U. S. in 1898, following the Spanish American War. During World War II, most of the original station was destroyed by American rear guard action and aircraft bombing attacks. Following World War II and the achievement of Philippine independence, a decision was made to establish a U. S. Naval Base at Subic Bay. Substantial construction efforts were begun and accelerated during the Korean Conflict, resulting in the establishment of the U. S. Naval Base, Subic Bay, in 1954. Much of the area now occupied by the Freeport was previously occupied by the City of Olongapo. At that time, the Commander of the Naval Base was also in control of the City of Olongapo. During the Vietnam Conflict, construction of the facilities was again accelerated, and...

Words: 8493 - Pages: 34

Premium Essay

Project Management

...purchases and last but not least a food deliverer who will be working explicitly with awaiting supplies. The client will be able to view the food items, sign-up and place the order. There will be a verification invoice (printable) for each and every purchase hat is made by the client. The development of this project will be determined by Software Development Life Cycle (SDLC) with HTML and PHP as the development 'languages' while MySQL server will be used as the data source of the project. HTML language is beneficial due to its simple to use and understand approval qualities while MySQL has better innovative functionalities and qualities, is free, has good protection and possess interoperability. The benefits of using PHP language in developing this project comprise: • It is a constant free language developed and managed by a large team of PHP designers which assist in forming a maintenance community and numerous expansion libraries. • It is simple and fast to learn and adopt. • It can be executed on numerous systems, therefore, simple for users to discover hosting solutions. • It has integral data source connection...

Words: 2990 - Pages: 12

Premium Essay

Bdjobs Training

... Management Development and so forth. Since its inception, Bdjobs Training has been mentoring the professionals by providing latest industry focused education. BT, in this expedition, engages hundreds of industry experts to ensure quality education to the young entrepreneurs and professionals of the country. BT offers both short (1 or 2 days) and long courses in the form of workshop and certificate training. Also BT offers customized in-house training programs exclusively designed for a group of employees. Customized courses can be provided either at our training facilities or on-site at clients’ location. Our training programs are lively, interactive, and include role-playing and demonstrations of real-life workplace issues and solutions. bdjobstraining.com Page |2 bdjobstraining.com Page |3 TRAINING TRACKS Marketing/ Sales Track • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 1111 Selling Techniques for Excellence 13 Lessons to turn every Company into Fantastic Brands Advance Selling Techniques Art of Pharmaceutical Sales Brand Management–Walking the Talk Branding for Bangladeshi Business Constructive & Modern Leadership Approach in Selling through Team Building Corporate Sales Management for Excellence Creating New Prospects and Managing Sales Pipeline Creative & Successful Selling Techniques for Excellence Customer Relationship Management (CRM) Digital / On-line Marketing - New Era of Brand Management Effective...

Words: 2551 - Pages: 11

Premium Essay

Lrt Research Paper

...1.1 COMPANY PROFILE The idea of The Healthy Potato shop was conceived by Lance Kerwin Gagalang, Kyle Aldrich Mercado, and Bernard Dennis J. Chu, Marketing students from Colegio De San Juan De Manila. The Business was created because of the issues of factory made products being unhealthy. The firm decided to come up with delicious yet healthy snacks that eliminated health concerning issues that are produced at present. 1.2 NATURE OF PRODUCT Potato Heads product idea came from the owner’s passion for Healthy but delicious foods. Potato Head will be offering different kinds of Healthy Snack products. Potato Products that consumer will love and patronize. Potato Head’s products include the following: * French Fries - That will have different variants of flavor such as: 1. Cheese, Barbeque-Spiced French Fries, Garlic Fries * Mojos – Healthy made mojos with Original, Barbeque and Cheese flavours. * Twister Fries – twister Fries with optional flavours and dips. 1.3 SIZE AND GROWTH TREND OF THE MARKET SCHOOL | 2014 | 2015 | GROWTH RATE | Colegio de San Juan de Letran | 9, 554 | 9, 936 | 4% | Lyceum of the Philippines | 16, 383 | 17, 529 | 2% | Mapua Institute of Technology | 10, 672 | 10, 885 | 6% | PamantasanLungsod ng Maynila | 10, 301 | 10, 507 | 2% | Source: Intramuros Administration The figures cited above represents the size and growth trend of the target market in a particular school. The Healthy Potato will be offered in front...

Words: 4998 - Pages: 20

Free Essay

Marketing

...I. Executive Summary A. Brief Description of Products and Services The JNJ Enterprises produces chairs which will be selling to its consumers. The name of their product is called “WELL CHAIR”. The positioning statement of JNJ Enterprises is “WELL CHAIR with CARE”, C for CLASS, A for AFFORDABILITY, R for RECYCLABILITY, E FOR ENVIROMENTAL CARE. “WELLCHAIR” is a product that has unique design which their customer will greatly benefit from their quality products in terms of, comfort, and appreciation of the room environment. “WELLCHAIR” helps to decorate homes in very attractive designs and it helps to create pleasant, productive office environments with well-designed furniture that transforms a simple room into the classic mode, in which people can stay. Also in home decoration “WELLCHAIR” helps to spend a happy moment together with their family. The JNJ Enterprises always provide the best possible value to their customers who care about quality office environments and home decorations. The features of their products are the following: (1) backside of the chair (rattan plastic) – it has the function to lean on and it has benefits for comfort and relaxation. (2) the seat (made of tire/foam/rubber)- has the function to sit onto and has mini cabinet to put the things and has benefit to relax and to feel relieve and at the same there is an organizer inside the tire. (3) leg extender- which has a function of extending your legs and has a benefits of comfort...

Words: 8798 - Pages: 36

Premium Essay

Final Paper

...ECOMMER In partial fulfillment of the requirements in E-commerce (ECOMMER) Submitted to: Mr. Jaime Borromeo Submitted by: K32 Term 2, A.Y. 2015-2016 I. Company Background bookcop.com is a start-up conceptualized by four business students from De La Salle University who all intend to apply what they have been learning so far and have a stable source of income, at the same time. Eyeing on providing value to their fellow students through their business, they had identified that one problem that is consistent in the school setting is the need for cheaper, but legitimate textbooks. The group saw that majority of the courses require textbooks and not all students are able to get their own copy on time for a number of reasons. Some of which are bookstores not having enough stocks and students themselves are unwilling to spend much money on books. This problem was considered an opportunity by the young entrepreneurs, and not so long after months of brainstorming and conceptualizing, there was the birth of bookcop.com. bookcop.com will serve as an online marketplace and bridge where students from different schools, colleges and universities in Metro Manila are able to make selling, and renting transactions of college textbooks with other college students from their own school or from others. With bookcop.com, not only are cheaper books a step nearer to students, but the transactions are more convenient to do and are easily reviewed and retrieved for they...

Words: 9463 - Pages: 38

Free Essay

A Feasibility Study on the Commercialization of the Coconut Cream Pie

...CHAPTER 1 INTRODUCTION Brief Background of the Study The Philippines remains as the world leading supplier of traditional coconut products. The Industry is also finding new products and uses for the “Tree of Life”: Coco Peat, geotextiles, activated carbon and virgin coconut oil. The coconut industry is a dominant sector of Philippine agriculture composes of 12 Million Hectare of farm lands, 3.25 Million is devoted to coconut and 68 out of 79 provinces are coconut areas. One of the provinces that have an abundant supply of coconut is Tagaytay. Coconut industry gives an opportunity for the locals to create and develop a lot of products that is made from coconut. The coconut is known for its great versatility as seen the many domestic, commercial, and industrial uses of its different parts. Coconuts are part of the daily diet of many people, which lead to the reinvention of an ordinary Cream Pie into Coconut Cream Pie. The original ingredients of Coconut Cream Pie are package refrigerated pie crusts sugar, cornstarch, egg yolks, butter, sweetened flaked coconut, vanilla extract, and whipping cream. Marisol Amparo Habelito, an entrepreneur, comes up with the idea on how to make the procedures of the Coconut Cream pie become easier and affordable. Instead of using expensive ingredients, Marisol used crushed biscuits, filling of sweetened strips of coconut meat and heavy cream on top as alternative ingredients. The Coconut Cream Pie by Marisol Amparo Habelito was initially sold...

Words: 8008 - Pages: 33

Free Essay

Pork Barrel: to Be Abolished or Not

...A RESEARCH PAPER PORK BARREL: TO BE ABOLISHED OR NOT OUTLINE Thesis : The recent scandal of government officials allegedly channelling their pork barrel funds to fake non-governmental organizations with nothing but ghost projects to show for has yet again raised the issue of abolishing the pork barrel. I. Introduction to Pork Barrel A. Definition of Terms B. PDAF in the Philippines C. Importance of PDAF II. PDAF scam A. People involved B. Reactions and Protests III. Abolishment of Pork Barrel A. Benefits B. Consequences C. Alternatives D. Opinions about the issue E. What the government will do after abolishing the Pork Barrel IV. Conclusion  V. Recommendation I. Introduction to Pork Barrel A cure, a treat, an alliance, a devastation or just a play. What do we really know about that so called Pork Barrel? A. Definition of Terms The Priority Development Assistance Fund (PDAF) is a discretionary fund in the Philippines available to members of Congress. Originally established as the Countrywide Development Fund (CDF) in 1990, it is designed to allow legislators to fund small-scale infrastructure or community projects which fell outside the scope of the national infrastructure program, which was often restricted to large infrastructure items (Nograles and Lagman ). The PDAF is commonly called the "pork barrel", and has been the subject of much public criticism following exposés on abuses perpetuated by members of Congress on use of the fund...

Words: 4110 - Pages: 17