S
S
SayrusCraft2018-11-21 13:06:54
PHP
SayrusCraft, 2018-11-21 13:06:54

What is the best way to implement a class to work with a user?

Good day everyone!
I recently started learning OOP and now it's time to put it into practice. But since my knowledge is purely theoretical, I cannot say with certainty what I am doing right.
The task is as follows:
- get the user's cookies;
- pass cookies through filters;
- check cookies for validity with user data;
- get the data of an authorized user to work with them;
Here is the class that I have implemented:

class player
{

private static $instance;
private static $data;

private function __construct()
{

if(!empty($_COOKIE['pid']) && !empty($_COOKIE['key']))
{

if(preg_match('/^[0-9]{1,6}$/', $_COOKIE['pid']) && preg_match('/^[0-9]{1,6}$/', $_COOKIE['key']) && preg_match('/^[0-9]{0,1}$/', $_COOKIE['new']))
{


if($_COOKIE['new'] != 1) { $dir = 'base'; } else { $dir = 'new'; }

$session = 'ldb/sessions/'.$dir.'/'.$_COOKIE['pid'].'/'.md5($_COOKIE['key'].$_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']).'/';

if(is_dir($session))
{

require_once $session."a.php";

self::$data = array('id' => $a[0],'type' => $a[1],'nick' => $a[2]);

}
else
{
// удалить куки
}

}
else
{
// удалить куки
}

}

}
private function __clone() {}

public static function instance()
{

if(empty(self::$instance))
{

self::$instance = new self();

return self::$instance;

}

}

public static function data($arg)
{
$return = self::$data[$arg];
return $return;
}

}

The code works, but did I use OOP correctly for the given task?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2018-11-21
@SayrusCraft

Unfortunately just a class similar to a singleton.
if for good,
then you first need to make the Storage interface, which will regulate the work with the storage,
then you need to make a class based on this interface that will work with COOKIE, that is, save and retrieve any data from this storage,
then make your player class in the parameters of the constructor, specify Storage which subsequently, the necessary storage will be injected (in this case, for working with cookies)
This

if(is_dir($session))
{
require_once $session."a.php";
....
}

In general, a complete poison, so you will not find it in any book on OOP. Your object should be as little dependent on third-party classes and modules as possible (preferably only on abstractions as indicated above with Storage)
PS and in general it is better to do autoload and switch to namespaces.

A
atawerrus, 2018-11-21
@atawerrus

This is not OOP code at all, it just takes some pattern and procedural code in methods.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question