Week 5.pdf
Document Details
Uploaded by ZippyPelican
Tags
Full Transcript
CP476 Internet Computing Week 5 – 1 PHP – Object-Oriented Programming Shaun Gao, Ph.D., P.Eng. Agenda PHP OOP Constructure/destructor Access modifier - visibility Constants Static Properties and Methods Inheritance Polymorphism Overloading Overriding Abstract classes Interface summary PHP OOP – Cons...
CP476 Internet Computing Week 5 – 1 PHP – Object-Oriented Programming Shaun Gao, Ph.D., P.Eng. Agenda PHP OOP Constructure/destructor Access modifier - visibility Constants Static Properties and Methods Inheritance Polymorphism Overloading Overriding Abstract classes Interface summary PHP OOP – Constructor Constructors: it is a special method that gets called automatically when you create a new object. It's useful for initializing the object's properties or performing other setup tasks. In PHP, constructors are defined using the __construct() method. Example: class Car { public $make; public $model; public $year; public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $myCar = new Car(‘Honda', ‘HRV', 2022); $this->year = $year; echo "Make: ". $myCar->make. "\n"; } echo "Model: ". $myCar->model. "\n"; } Demo 1 echo "Year: ". $myCar->year. "\n"; PHP OOP - Destructor Destructors: it is another special method that gets called automatically when an object is destroyed or when the script ends. It's useful for cleaning up resources or performing other tasks before the object is removed from memory. In PHP, destructors are defined using the __destruct() method. Example: class Car { public $make; public $model; public $year; public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } public function __destruct() { echo "The ". $this->make. " ". $this->model. " object has been destroyed.\n"; } } PHP OOP - Access Modifiers - visibility Properties and methods can be declared as Public: accessible everywhere Private: accessible only within the same class Protected: accessible only within the class itself and by inheriting and parent classes For properties, a visibility declaration is required For methods, a visibility declaration is optional; by default, methods are public Accessing a private or protected property/method outside its visibility is a fatal error PHP OOP - Access Modifiers – visibility – cont. Example: Demo 2: class Vis { public $public = 1; private $private = 2; protected $protected = 3; protected function proFc () {} private function priFc () {} } $v = new Vis (); echo $v - > public ; # prints 1 echo $v - > private ; # Fatal Error echo $v - > protected ; # Fatal Error echo $v - > priFc (); # Fatal Error echo $v - > proFc (); # Fatal Error PHP OOP - Constants Classes can have their own constants and constants can be declared to be public, private or protected; by default, class constants are public Accessing a private or protected constant outside its visibility is a fatal error ; execution of the script stops Class constants are allocated once per class, and not for each class instance class MyClass { Class constants are accessed using the scope const SIZE = 10; resolution operator :: } Demo 3 echo MyClass :: SIZE ; # prints 10 $o = new MyClass (); echo $o :: SIZE ; # prints 10 PHP OOP - Static Properties and Methods Class properties or methods can be declared static Static class properties and methods are accessed (via the class) using the scope resolution operator :: Static class properties cannot be accessed via an instantiated class object, but static class methods can Static class method have no access to $this Demo 4: class Employee { static $totalNumber = 0; public $name ; function __construct ( $name ) { $this - > name = $name ; Employee :: $totalNumber ++; }} $e1 = new Employee ( " Ada " ); $e2 = new Employee ( " Ben " ); echo Employee :: $totalNumber; PHP OOP - Inheritance When a class derives from another class, the child class will inherit all the public and protected properties and methods from the parent class. The child class can have its own properties and methods. In PHP, An inherited class is defined by using the extends keyword. Example: Demo05: PHP OOP – Inheritance – cont. Demo06: class Rectangle { protected $height ; protected $width ; function __construct ( $height , $width ) { $this - > height = $height ; $this - > width = $width ; } function area () { return $this - > width * $this - > height ; } } class Square extends Rectangle { function __construct ( $size ) { parent :: __construct ($size , $size ); } } $rt1 = new Rectangle (3 ,4); echo " The area = " ,$rt1 - > area () , " \ n " ; $sq1 = new Square (5); echo “The square area = " ,$sq1 - > area () , " \ n " PHP OOP – Inheritance – cont. PHP - Overriding Inherited Methods Inherited methods can be overridden by redefining the methods (use the same name) in the child class. PHP - The final Keyword The final keyword can be used to prevent class inheritance or to prevent method overriding. Demo07: PHP OOP – Polymorphism Polymorphism = many forms Polymorphism refers to a programming language’s ability to process objects differently depending on their data types or class. Overloading Overriding PHP OOP – Polymorphism – cont. Overloading PHP has an alternative way to achieve method overloading by using variable parameters functionality. Demo08 Method overloading class TestP1 { function example(...$args) { $retV = count($args); return $retV; } } $obj = new TestP1(); $rt1 = $obj->example(1, 2); echo $rt1. "\n"; $rt2 = $obj->example(1, 2, 3, 4, 5, 6, 7); echo $rt2. "\n"; PHP OOP – Polymorphism – cont. PHP provided Method overloading __call() is triggered when invoking inaccessible methods in an object context. __callStatic() is triggered when invoking inaccessible methods in a static context. demo09 class MethodTest { public function __call($name, $arguments) { echo "Calling object method '$name' ". implode(', ', $arguments). "\n"; } public static function __callStatic($name, $arguments) { echo "Calling static method '$name' ". implode(', ', $arguments). "\n"; } } $obj = new MethodTest; $obj->runTest('in object context'); MethodTest::runTest('in static context'); PHP OOP – Polymorphism – cont. Overriding Method overriding in PHP involves providing a specific implementation of a method in a child class that differs from the implementation in the parent class. Demo10 class parentC { function func1($name) { echo "Hello ". $name. "\n"; } } class childC extends parentC { function func1($name) { echo "Hi ". $name. "\n"; } } $obj1 = new childC(); $obj1->func1("John"); $obj2 = new parentC(); $obj2->func1("Mary"); PHP OOP - Abstract Classes Abstract Classes: it is a class that contains at least one abstract method. Abstract methods: it is a method that is declared, but not implemented in the code. An abstract class or method is defined with the abstract keyword: Example: PHP OOP - Abstract Classes – cont. when a child class is inherited from an abstract class, the following rules must be followed: The child class method must be defined with the same name and it redeclares the parent abstract method The child class method must be defined with the same or a less restricted access modifier The number of required arguments must be the same. However, the child class may have optional arguments in addition Demo11: PHP OOP - Interfaces Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword. Interfaces are similar to abstract classes. The difference is as follows: Interfaces cannot have properties, while abstract classes can All interface methods must be public, while abstract class methods can be public or protected All methods in an interface are abstract, so the abstract keyword is not necessary while all methods in an abstract class are not necessary to be abstract. Classes can implement an interface while inheriting from another class at the same time To implement an interface, a class must use the implements keyword. PHP OOP – Interfaces – cont. Example Demo12: Summary PHP OOP Concept Classes and objects Constructure/destructor Access modifier - visibility Constants Inheritance Polymorphism Overloading Overriding Abstract classes Interface Announcement Please let me know if you need help for the group project Test 1 on Friday (Feb 9), please bring your laptop PC. CP476 Internet Computing Week 5 – 2 PHP – DB connection Shaun Gao, Ph.D., P.Eng. Agenda PHP and DB connection Introduction Connections Queries and Processing of Results Prepared Statements PHP MySQL Database MySQL is a relational database system used on the web, it runs on a server, it is free to download and use, it uses standard SQL, it is very fast, reliable, and easy to use. Run SQL using PHP PHP Connect to MySQL There are two methods that connect to MySQL MySQLi extension (the "i" stands for improved) PDO (PHP Data Objects) MySQLi Installation: After you install PHP, you will find “php_mysqli.dll” under the folder “ext”. If you cannot find the file, please visit the following URL for reference. http://php.net/manual/en/mysqli.installation.php PDO Installation: https://www.php.net/manual/en/pdo.installation.php php.ini update by adding the following in Windows, then restart Apache extension=php_mysqli.dll extension=php_pdo_mysql.dll PHP Connect to MySQL – cont. MySQLi vs PDO Functionalities are similar: provide a way to connect DB from web server to DB server. The main difference between PDO and MySQLi is that PDO supports 12 different Database systems MySQLi, which supports MySQL only. PHP - Open a Connection to MySQL Use MySQLi mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try { $conn = new mysqli("localhost", "username", "password", "databaseName"); if ($conn->connect_error) { die("Connection failed: ". $conn->connect_error); } $conn->set_charset("utf8mb4"); } catch(Exception $e) { error_log($e->getMessage()); exit('Error connecting to database'); } $conn->close(); Demo01, demo01-1: PHP - Open a Connection to MySQL - PDO Use PDO $dsn = "mysql:host=localhost;dbname=users;charset=utf8mb4"; $options = [ PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array ]; try { $conn = new PDO($dsn, “root", “Isucceed168", $options); } catch (PDOException $e) { error_log($e->getMessage()); exit('Something wrong'); //something a user can understand } $conn=null; Demo 2: PHP - Create a MySQL Database A database consists of one or more tables. Use MySQLi // Create database after successful connection $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: ". $conn->error; } $conn->close(); Demo03: PHP - Create a MySQL Database - PDO Use PDO try { …… $sql = "CREATE DATABASE myDBPDO"; // use exec() because no results are returned $conn->exec($sql); echo "Database created successfully \n"; } catch(PDOException $e) { error_log($e->getMessage()); exit(‘Database creation failed'); } $conn=null; Demo04: PHP - MySQL Create Table The CREATE TABLE statement is used to create a table in MySQL Use MySQLi … connection succeeded $sql = "CREATE TABLE MyGuests (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: ". $conn->error; } $conn->close(); Demo05 PHP - MySQL Create Table - PDO The CREATE TABLE statement is used to create a table in MySQL Use PDO … connection succeeded Try{ $sql = "CREATE TABLE MyGuestsPDO (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; // use exec() because no results are returned $conn->exec($sql); echo "Table MyGuests created successfully"; } catch(PDOException $e) { echo $sql. '\r\n'. $e->getMessage(); } $conn = null; Demo06 PHP – MySQL Insert Use MySQLi … connection succeeded, $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: ". $sql. “\n". $conn->error; } $conn->close(); Demo07 PHP – MySQL Insert – PDO. Use PDO … connection succeeded Try{ $sql = "INSERT INTO MyGuestsPDO (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; // use exec() because no results are returned $conn->exec($sql); echo "New record created successfully \n"; } catch(PDOException $e) { echo $sql. “\r\n". $e->getMessage(); } $conn = null; Demo08 PHP – Prepared statement for SQL Benefit of using prepared statements. You can execute SQL statements repeatedly with high efficiency. Demo09 Prepared statements are secure – it can prevent SQL injection attacks Prepared statement variations PHP – MySQL Prepared – cont. A prepared statement is a technique used to execute the same (or similar) SQL statements repeatedly with high efficiency. Procedures: Prepare: SQL query with empty values as placeholders with either a question mark or a variable name. “INSERT INTO MyGuests VALUES(?, ?, ?)” Bind: Bind values or variables to the placeholders. Execute: Execute query simultaneously. API of MySQLi $sql = $conn->prepare("INSERT INTO myguests(firstname, lastnamen, email) VALUES (?, ?, ?)"); $sql->bind_param(“sss", $fn, $ln, $email); // “sss" means that $fn, $ln and $email as a string $fn = “Mary”; $ln = “Gao”; $email = “[email protected]”; $sql->execute(); Demo09-1 PHP – MySQL Prepared – cont. Benefits of using prepared SQL statements Prepared statements are very useful against SQL injection attacks. Prepared statements reduce parsing time as the preparation on the query is done only once when same SQL statements need to execute repeatedly. Minimize bandwidth to the server as you need send only the parameters each time, and not the whole SQL statements. $stmt->bind_param("sss", $firstname, $lastname, $email); i - integer d - double s - string b – BLOB ((binary large object) is a varying-length binary string that can be up to 2,147,483,647 characters long) PHP – MySQL Prepared – cont. API of PDO …… connection succeeded // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"); $stmt->bindParam(':firstname', $firstname); $stmt->bindParam(':lastname', $lastname); $stmt->bindParam(':email', $email); $firstname = “Mary"; $lastname = “Gao"; $email = “[email protected]"; $stmt->execute(); Demo10 PDO and MySQLi prepared statements Prepared statements PDO supports named parameters Syntax: : var_name PDO and MySQLi support Positional parameters Syntax: ? (Note: PDO does not allow using named and positional parameters in same query) Demo11 PDO vs. MySQLi PDO differs from MySQLi Named parameters Positional parameters MySQL server supports using anonymous, positional placeholder with ?. (Note: PDO does not allow using named and positional parameters in same query) Prepared statements https://www.php.net/manual/en/mysqli.quickstart.preparedstatements.php Summary PHP MySQL Connections MySQLi PDO