Phát triển ứng dụng mã nguồn mở - Bài 2.3: PHP object oriented proramming

$_GET và $_ • $_GET: array of variables passed to the current script via the URL parameters (the HTTP GET method).

Test GET • $_POST: array of variables passed to the current script via the HTTP POST method. • With the HTTP GET method, the length of URL is limited (the maximum characters of URL length is 2048? 4096? 8192?, )

pdf65 trang | Chia sẻ: thuychi16 | Lượt xem: 635 | Lượt tải: 1download
Bạn đang xem trước 20 trang tài liệu Phát triển ứng dụng mã nguồn mở - Bài 2.3: PHP object oriented proramming, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Đoàn Thiện Ngân Bài 2.3 - 1/65 Bài 2.3: PHP Object Oriented Proramming GV: ĐOÀN THIỆN NGÂN Đoàn Thiện Ngân Bài 2.3 - 2/65 Nội dung • Arrays $_POST - $_GET • Cookies - Sessions • PHP Object oriented solutions. Đoàn Thiện Ngân Bài 2.3 - 3/65 Tài liệu tham khảo 1. Bắt buộc: PHP Manual. 2. PHP Objects, Patterns, and Practice, 3rd Edition, Matt Zandstra, Apress, 2010. 3. Learning PHP Design Patterns, William Sanders, O'REILLY, 2013 Đoàn Thiện Ngân Bài 2.3 - 4/65 $_GET và $_POST • $_GET: array of variables passed to the current script via the URL parameters (the HTTP GET method). Test GET • $_POST: array of variables passed to the current script via the HTTP POST method. • With the HTTP GET method, the length of URL is limited (the maximum characters of URL length is 2048? 4096? 8192?, ) ... Đoàn Thiện Ngân Bài 2.3 - 5/65 testpost.html <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> Feedback Form Please complete this form to submit our feedback: Test GET by Hyperlink Name: Mr. Mrs. Ms. Đoàn Thiện Ngân Bài 2.3 - 6/65 testpost.html (tt) Email Address: <input type="text" name="email" size="20" /> Response: This is... <input type="radio" name="response" value="excellent" /> excellent <input type="radio" name="response" value="okay" /> okay <input type="radio" name="response" value="boring" /> boring Comments: <textarea name="comments" rows="3" cols="30"> <input type="submit" name="submit" value="Send My Feedback" /> Đoàn Thiện Ngân Bài 2.3 - 7/65 action.php if (count($_POST) > 0) { print "array POST:"; print_r($_POST); echo "",'...Display in details array $_POST'; foreach ($_POST as $key => $value) print ('' . $key . ' = ' . $value); } if (count($_GET) > 0) { print 'array GET:'; print_r($_GET); echo "",'...Display in details array $_GET'; foreach ($_GET as $key => $value) print ('' . $key . ' = ' . $value); } Đoàn Thiện Ngân Bài 2.3 - 8/65 Cookies và Sessions • How to maintain “state” as the user traverses a multipage Web site. • HTTP is a stateless technology, • HTTP has no built-in method for tracking a user or remembering data from one page of an application to the next. • E-commerce applications, user registration and login systems, and other common online services rely on being able to follow the same user from page to page. • Fortunately, maintaining state is quite simple with PHP. This part discusses the two primary methods for tracking data: cookies and sessions. Đoàn Thiện Ngân Bài 2.3 - 9/65 What Are Cookies • Cookies are simply a way for a server to store information on the user’s computer. By doing so, the server can remember the user over the course of a visit or through several visits. • Think of a cookie like a name tag: we tell the server our name, and it gives we a name tag. Then it can know who we are by referring back to the name tag. This brings up another point about the security issues involved with cookies. • Cookies have gotten a bad rap because users believe cookies allow a server to know too much about them. However, a cookie can only be used to store information that we give it, so it’s as secure as we want it to be. Đoàn Thiện Ngân Bài 2.3 - 10/65 Cookies between Server and Client Đoàn Thiện Ngân Bài 2.3 - 11/65 Creating Cookies • An important thing to understand about cookies is that they must be sent from the server to the client prior to any other information. • This means a script should send cookies before any print statement, before including an external file that contains HTML, and so forth. • Should the server attempt to send a cookie after the Web browser has already received HTML—even an extraneous white space—an error message will result and the cookie won’t be sent. This is by far the most common cookie-related error. • Cookies are sent using the setcookie() function: setcookie(name, value); setcookie('CookieName', 'This is the cookie value.'); Đoàn Thiện Ngân Bài 2.3 - 12/65 Creating Cookies • We can continue to send more cookies to the browser with subsequent uses of the setcookie() function setcookie('name2', 'some value'); setcookie('name3', 'another value'); • Finally, when creating cookies, we can— as we’ll see in this example—use a variable for the name or value attribute of our cookies: setcookie($cookie_name, $cookie_value); Đoàn Thiện Ngân Bài 2.3 - 13/65 Reading from Cookies • The setcookie() function places cookie data in the $_COOKIE array. • To retrieve a value from a cookie, refer to the cookie name as the index of this array. • For Ex, with the line setcookie('user', 'trout'); we would use $_COOKIE['user']. • Unless we change the cookie’s parameters (as we’ll see later in this chapter), the cookie will automatically be accessible to every other page in our Web application. • We should understand, however, that a cookie is never accessible to a script immediately after it’s been sent. Đoàn Thiện Ngân Bài 2.3 - 14/65 Adding Parameters to a Cookie • Although passing just the name and value arguments to the setcookie() function will suffice for most of our cookie uses, we ought to be aware of the other arguments available. • The function setcookie() can take up to five more parameters, each of which limits the operation of the cookie: setcookie(name, value, expiration, path, domain, secure, httponly); Đoàn Thiện Ngân Bài 2.3 - 15/65 Adding Parameters to a Cookie • The expiration argument is used to set a specific length of time for a cookie to exist. • If it isn’t specified, the cookie will continue to be functional until the user closes the browser. • Normally, we set the expiration time by adding a particular number of minutes or hours to the current time (using the time() function). This line of code sets the expiration time of the cookie to be one hour (3600 seconds) from the current moment: setcookie(name, value, time()+3600); Đoàn Thiện Ngân Bài 2.3 - 16/65 Adding Parameters to a Cookie • The path and domain arguments are used to limit a cookie to a specific folder in a Web site (the path) or to a specific domain. • Using the path option, we could limit a cookie to exist only while a user is in a specific subfolder of the domain: setcookie(name,value,time()+3600,'/subfolder/'); • Cookies are already specific to a domain, so the domain argument might be used to limit a cookie to a subdomain, such as forum.example.com. setcookie(name, value, time()+3600, '', 'forum.example.com'); Đoàn Thiện Ngân Bài 2.3 - 17/65 Adding Parameters to a Cookie • The secure value dictates that a cookie should only be sent over a secure HTTPS connection. A value of 1 indicates that a secure connection must be used, whereas 0 indicates that a secure connection isn’t necessary. • we could ensure a secure cookie transmission for e- commerce sites: setcookie('cart', '82ABC3012', . time()+3600, ', 'shop.example.com', 1); • We must pass all the values in order. If there’s no need to specify (or limit) the path, we use empty quotes. With the path argument, we can also use a single slash (/) to indicate the root folder (i.e., no path restriction). By doing so, we maintain the proper number of arguments and can still indicate that an HTTPS connection is necessary. Đoàn Thiện Ngân Bài 2.3 - 18/65 Adding Parameters to a Cookie • The final argument—httponly—was added in PHP 5.2. It can be used to restrict access to the cookie (for example, preventing a cookie from being read using JavaScript) but isn’t supported by all browsers. • Let’s add an expiration date to the existing page so that the user’s preferences will remain even after they’ve closed their browser and then returned to the site later. setcookie(name, value, time()+10000000, '/', '', 0); setcookie(name, value, time()+10000000, '/', '', 0); Đoàn Thiện Ngân Bài 2.3 - 19/65 Deleting a Cookie • Although a cookie automatically expires when the user’s browser is closed or when the expiration date/time is met, sometimes we’ll want to manually delete the cookie as well. • setcookie() can take up to seven arguments, but only one is required— the name. If we send a cookie that consists of a name without a value, it will have the same effect as deleting the existing cookie of the same name. • To delete the username cookie, we code setcookie('name', ''); or setcookie('name', FALSE); Đoàn Thiện Ngân Bài 2.3 - 20/65 Deleting a Cookie • As an added precaution, we can also set an expiration date that’s in the past: setcookie('username', FALSE, time() - 600); • The only caveat when it comes to deleting a cookie is that we must use the same argument values that were used to set the cookie in the first place (aside from the value and expiration). For example, if we set a cookie while providing a domain value, we must also provide that value when deleting the cookie: setcookie('user','lary',time() + 3600,'','a.com'); setcookie('user', '', time() - 600, '', 'a.com'); Đoàn Thiện Ngân Bài 2.3 - 21/65 What Are Sessions? • A session, like a cookie, provides a way for we to track data for a user over a series of pages. The difference between the two is that a cookie stores the data on the client (in the Web browser), whereas the session data is stored on the server. Because of this difference, sessions have numerous benefits over cookies: • Sessions are generally more secure, because the data is not transmitted back and forth between the client and server repeatedly. • Sessions allow we to store more information than we can in a cookie. Đoàn Thiện Ngân Bài 2.3 - 22/65 What Are Sessions? • Sessions can be made to work even if the user doesn’t accept cookies in their browser. • When we start a session, PHP generates a random session ID. Each user’s session will have its own session ID, corresponding to the name of the text file on the server that stores the user’s session data. • So that every PHP script on a site can associate the same session data with a particular user, the session ID must be tracked as well. By default, this session ID is sent to the Web browser as a cookie. Subsequent PHP pages will use this cookie to retrieve the session ID and access the session information. Đoàn Thiện Ngân Bài 2.3 - 23/65 Creating a Session • Creating, accessing, or deleting a session begins with the session_start() function. This function will attempt to send a cookie the first time a session is started, so it absolutely must be called prior to any HTML or white space being sent to the Web browser. Therefore, on pages that use sessions, we should call the session_start() function as one of the very first lines in our script: <?php session_start(); • The first time a session is started, a random session ID is generated and a cookie is sent to the Web browser with a name of PHPSESSID (session name) and a value like 4bcc48dc87cb4b54d63f99da23fb41e1. Đoàn Thiện Ngân Bài 2.3 - 24/65 Creating a Session • Once the session has been started, we can record data to it by assigning values to the $_SESSION array: $_SESSION['first_name'] = 'Sam'; $_SESSION['age'] = 4; • Unlike with other arrays we might use in PHP, we should always treat this array as an associative array. In other words, we should explicitly use strings for the keys, such as first_name and age. • Each time a value is assigned to the $_SESSION array, PHP writes that data to a temporary file stored on the server Đoàn Thiện Ngân Bài 2.3 - 25/65 Accessing Session Variables • Now that we’ve stored values in a session, we need to know how to access them. • The first step is to invoke the session_start() function. This is necessary on every page that will make use of sessions, whether it’s creating a new session or accessing an existing one. • From there it’s simply a matter of referencing the $_SESSION variable as we would any other array. session_start(); print 'Hello, ' . $_SESSION['email']; Đoàn Thiện Ngân Bài 2.3 - 26/65 Deleting a Session • It’s important to know how to delete a session, just as it’s important to know how to delete a cookie: Eventually we’ll want to get rid of the data we’ve stored. • Session data exists in two places—in an array during the execution of the script and in a text file, so we’ll need to delete both. • But first we must begin with the session_start() function, as always: session_start(); • Then, we clear the session variables by resetting the $_SESSION array: $_SESSION = array(); • Finally, remove the session data from the server (where it’s stored in temporary files). To do this, use session_destroy(); Đoàn Thiện Ngân Bài 2.3 - 27/65 Object-Oriented PHP • General concepts • Classes and Objects • Properties • Methods - Constructor • Inheritance - Child classes Đoàn Thiện Ngân Bài 2.3 - 28/65 WHY OBJECT-ORIENTED PHP? • PHP is not an object-oriented language, but it does have extensive object-oriented features. • OOP approach has two distinct advantages: – Code reusability: Breaking down complex tasks into generic modules makes it much easier to reuse code. Class files are normally separate from the main script, so they can be quickly deployed in different projects. – Easier maintenance and reliability: Each method defined in a class normally handles a single task. The modular nature of code stored outside the main script means that, if a problem does arise, we fix it in just one place. Once a class has been thoroughly tried and tested, we can treat it like a black box, and rely on it to produce consistent results. Đoàn Thiện Ngân Bài 2.3 - 29/65 Object Oriented PHP • The collection of related variables and functions gathered together as a class. • To use the variables and functions defined by a class, we create an instance of the class, which is referred to as an object. • The variables are called its properties, and the functions are referred to as methods. Three most important characteristics of OOP – Encapsulation – Polymorphism – Inheritance Another key concept is loose coupling - designing code so that changes in one part don’t cascade down through the rest of the code (PHP 5 or PHP 6). Đoàn Thiện Ngân Bài 2.3 - 30/65 Object Oriented PHP • Encapsulation: This hides the details from the end user and prevents direct access to key values. • Polymorphism: This means giving the same name to methods and properties that play similar roles in different classes. Polymorphism extends encapsulation by hiding the details of how individual methods work by using a common name. • Inheritance: New classes can be derived from existing ones, automatically inheriting all the methods and properties of the parent or superclass. The new class can not only add new properties and methods of its own, it can override those of its parent. Đoàn Thiện Ngân Bài 2.3 - 31/65 Creating classes and objects • PHP has many built-in classes, some of which we will use later in the course, such as DateTime, XMLWriter, and XMLReader. • The focus in this session is on building our own classes. Once a class has been defined, we use it in exactly the same way as any of the built-in ones. • Define a class called Product: class Product { // properties defined here // methods defined here } Đoàn Thiện Ngân Bài 2.3 - 32/65 Accessing to properties & methods PHP visibility (access control) modifiers • public: means the property or method can be accessed by any part of a script both inside and outside the class definition. All methods are regarded as public unless preceded by a different modifier. • protected: prevents external access to a property or method, but permits access internally and to parent and child classes. • private: Private properties and methods can be accessed only within the class where they are defined. Đoàn Thiện Ngân Bài 2.3 - 33/65 Access a protected/private property • To access a protected or private property, we need to create getter and setter methods inside the class file. Both use a special variable called $this (current object). public function getProductType() { return $this->_type; } public function setProductType($type) { $this->_type = $type; } • Both methods need to be accessed from outside the class, so their visibility is set to public. Although OOP refers to them as methods, they are, in fact, functions, and we use the function keyword in exactly the same way as in procedural code. Đoàn Thiện Ngân Bài 2.3 - 34/65 pos_Test.php <?php class pos_Test { //put our code here protected $_name = 'Anonymous'; public function SetTestName($name) { $this->_name = $name; } public function GetTestName() { return $this->_name; } } ?> Đoàn Thiện Ngân Bài 2.3 - 35/65 Test_Class.php <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> Test protected property <?php // put our code here require_once 'pos_Test.php'; $objTest = new pos_Test(); echo 'Original: ' . $objTest->GetTestName() . ''; $objTest->SetTestName('BigTest'); echo 'New : ' . $objTest->GetTestName() . ''; ?> Đoàn Thiện Ngân Bài 2.3 - 36/65 Constructor method • When we create an instance of a class, PHP automatically looks for the class’s constructor method (or constructor). As the name suggests, a constructor builds the object, applying default values and assigning to properties values passed to the class when an object is instantiated. • In many languages, the constructor is a method that shares the same name as the class (PHP 3 and 4). However, since PHP 5, the constructor for all classes is called __construct() (with two leading underscores). Using a constructor is optional, but most classes do use one. • For backward compatibility, PHP looks for a method with the same name as the class if it can’t find __construct(), but this might not always be the case, so we should always use __construct(). Đoàn Thiện Ngân Bài 2.3 - 37/65 Constructor method • The constructor works like a setter method, so any values passed to it as arguments can be assigned to properties by using $this to refer to the current object: public function __construct($value) { $this->_property = $value; } • The constructor method is used exclusively for creating a new object, so it should not use return Đoàn Thiện Ngân Bài 2.3 - 38/65 Class with Constructor class Pos_Product { // properties defined here protected $_type; protected $_title; // constructor public function __construct($type, $title) { $this->_type = $type; $this->_title = $title; } $product1 = new Pos_Product('Book', 'PHP Object- Oriented Solutions'); $product2 = new Pos_Product('DVD', 'Atonement'); Đoàn Thiện Ngân Bài 2.3 - 39/65 Inheritance The parent class (Product) contains the common features, which are inherited by the child classes (DVD, Book). Đoàn Thiện Ngân Bài 2.3 - 40/65 Define a child class • Simply use the extends keyword together with the name of the parent class: class ChildClassName extends ParentClassName { // class definition goes here } • The child class needs access to the file where the parent class is defined, so we need to include the parent file before defining the child class. We should normally use require_once to include the parent file. Đoàn Thiện Ngân Bài 2.3 - 41/65 Accessing a parent class’s methods and properties • The scope resolution operator is a pair of colons (::). The name of the class goes on the left side of the opera