- Access user class php
- Access user class php
- Фильтрация данных с помощью zend-filter
- Контекстное экранирование с помощью zend-escaper
- Подключение Zend модулей к Expressive
- Совет: отправка информации в Google Analytics через API
- Подборка PHP песочниц
- Совет: активация отображения всех ошибок в PHP
- PHP: Accessing Other Classes Properties and Methods
- Dependency injection in OOP
- Using singleton in PHP
Access user class php
INSIDE CODE and OUTSIDE CODE
class Item
/**
* This is INSIDE CODE because it is written INSIDE the class.
*/
public $label ;
public $price ;
>
/**
* This is OUTSIDE CODE because it is written OUTSIDE the class.
*/
$item = new Item ();
$item -> label = ‘Ink-Jet Tatoo Gun’ ;
$item -> price = 49.99 ;
?>
Ok, that’s simple enough. I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:
* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it — huge mistake.
* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) — another huge mistake.
Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that’s it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.
INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float — which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.
class Item
/**
* Here’s the new INSIDE CODE and the Rules to follow:
*
* 1. STOP ACCESS to properties via $item->label and $item->price,
* by using the protected keyword.
* 2. FORCE the use of public functions.
* 3. ONLY strings are allowed IN & OUT of this class for $label
* via the getLabel and setLabel functions.
* 4. ONLY floats are allowed IN & OUT of this class for $price
* via the getPrice and setPrice functions.
*/
protected $label = ‘Unknown Item’ ; // Rule 1 — protected.
protected $price = 0.0 ; // Rule 1 — protected.
public function getLabel () < // Rule 2 - public function.
return $this -> label ; // Rule 3 — string OUT for $label.
>
public function getPrice () < // Rule 2 - public function.
return $this -> price ; // Rule 4 — float OUT for $price.
>
public function setLabel ( $label ) // Rule 2 — public function.
/**
* Make sure $label is a PHP string that can be used in a SORTING
* alogorithm, NOT a boolean, number, array, or object that can’t
* properly sort — AND to make sure that the getLabel() function
* ALWAYS returns a genuine PHP string.
*
* Using a RegExp would improve this function, however, the main
* point is the one made above.
*/
if( is_string ( $label ))
$this -> label = (string) $label ; // Rule 3 — string IN for $label.
>
>
public function setPrice ( $price ) // Rule 2 — public function.
/**
* Make sure $price is a PHP float so that it can be used in a
* NUMERICAL CALCULATION. Do not accept boolean, string, array or
* some other object that can’t be included in a simple calculation.
* This will ensure that the getPrice() function ALWAYS returns an
* authentic, genuine, full-flavored PHP number and nothing but.
*
* Checking for positive values may improve this function,
* however, the main point is the one made above.
*/
if( is_numeric ( $price ))
$this -> price = (float) $price ; // Rule 4 — float IN for $price.
>
>
>
?>
Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you. which means you can keep your hair!
If you have problems with overriding private methods in extended classes, read this:)
The manual says that «Private limits visibility only to the class that defines the item». That means extended children classes do not see the private methods of parent class and vice versa also.
As a result, parents and children can have different implementations of the «same» private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent’s private methods. If the child doesn’t see the parent’s private methods, the child can’t override them. Scopes are different. In other words — each class has a private set of private variables that no-one else has access to.
A sample demonstrating the percularities of private methods when extending classes:
abstract class base <
public function inherited () <
$this -> overridden ();
>
private function overridden () <
echo ‘base’ ;
>
>
class child extends base <
private function overridden () <
echo ‘child’ ;
>
>
$test = new child ();
$test -> inherited ();
?>
Output will be «base».
If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That’s what it is for:)
A sample that works as intended:
abstract class base <
public function inherited () <
$this -> overridden ();
>
protected function overridden () <
echo ‘base’ ;
>
>
class child extends base <
protected function overridden () <
echo ‘child’ ;
>
>
$test = new child ();
$test -> inherited ();
?>
Output will be «child».
Access user class php
В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
Совет: активация отображения всех ошибок в PHP
При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.
PHP: Accessing Other Classes Properties and Methods
We can access other classes properties (variables) and methods (functions) by injecting the class object in the class that needs it.
In object orientated PHP (OOP), it may sometimes be desired to access methods from another classes, In this article we will discuss two ways to solve this problem.
Problem: A common beginner problem in OOP is how to access properties (variables) and methods (functions) from other classes without extending them. We actually have a few ways we can deal with this problem. The first, and recommended solution, is to use a technique called Dependency injection (DI), this technique allows us to split up our code and organize it in separate classes, which can then be independently instantiated.
When using DI we will usually be instantiating a class once in our composition root (I.e.: index.php), and then pass it on to subsequent classes that depend on it. Here is an example of how this technique may be used:
$db = new db_client(); $handle_users = new handle_users($db);
In this example, db_client() is an independent class shared by two or more objects. It should not be extended. Instead of extending it, we inject it in the classes that needs database access.
Inside handle_users(), the database object will be available in the __construct() magic method:
class handle_users private $db; public function __construct($db) $this->db = $db; > public function login_check() // $db->query(''); // . > >
Dependency injection in OOP
A recommended way to make one class depend on another, is by using constructor injection. The solution we discuss in this section will work in most situations. Let us start by imagining an independent class that is shared by multiple objects:
class db_client public $db_link; private $db_host = "localhost"; private $db_user = "Username"; private $db_pw = "Password"; private $db_name = "Database"; public function __construct() $this->db_link = @new mysqli($this->db_host, $this->db_user, $this->db_pw, $this->db_name); > >
Think of the db_client() class as a client to handle all the database stuff. Since it may be shared by many different projects or objects, we should try to make it an independent class.
We should not extend the db_client from the handle_users class, as it would make it too tightly coupled with the users-code, and ruin the portability of the db_client() class. Instead, we should use DI to provide the database object as a dependency for the user handler class upon instantiation.
Now, imagine we also make a handle_users class that deals with everything user related, such as creation of new users, logging in and out, etc. The handle_users class needs the db_client(); class to access the database. To do this, we may pass the db_client as a parameter when initializing the handle_users class:
class handle_users public $db; public function __construct($db) $this->db = $db; // Make $db available via "$this->db->your_function()" > public function $this->db->db_link->query('SELECT * FROM. '); // The db_client object used inside handle_users. > >
For this to work, we will need to first create an instance of the db_client class, and then pass it as a parameter when loading the handle_users class. I.e.:
require $_SERVER["DOCUMENT_ROOT"] . 'db_class.php'; // Handles the Database stuff require $_SERVER["DOCUMENT_ROOT"] . 'handle_users.php'; // All user related stuff $db = new db_client(); $handle_users = new handle_users($db);
__construct(); is a magic method that is automatically executed when you create an instance of your class. The $db object automatically becomes available inside the __construct method where we may assign it to a property (variable).
Using singleton in PHP
Another way to access methods in another class, is to use singleton. This makes it possible to use methods without the need to first instantiate the class. The object is instead created inside the class itself.
Note. Using singleton in PHP is not recommended.
A database class in singleton looks like this:
class db_client private static $instance = null; // Credentials private $db_host = "localhost"; private $db_user = "Username"; private $db_pw = "Password"; private $db_name = "Database"; public static function getInstance() if (self::$instance == null) self::$instance = new Singleton(); > return self::$instance; > public function getConnection() return $this->db_link; > private function __construct() $this->db_link = @new mysqli($this->db_host, $this->db_user, $this->db_pw, $this->db_name); > >
To perform a database query, simply do like this:
$db = db_client::getInstance(); $mysqli = $db->getConnection(); $result = $mysqli->query("SELECT foo FROM . ");
The __construct() method is declared private, which prevents creating an object from outside the class using the new operator. The object is instead created from within the getInstance() method.