나는 다소 그럴 수 있습니다. 나는 이것이 최선의 방법인지 확실하지 않지만 그것이 나를 위해 일한다.
내 factory 클래스는 내 코드의 핵심입니다. 여기에서 나는 함께 일하는 모든 수업을 생성한다. 내 팩토리 클래스는 별도의 파일 factory.class.php
에 저장됩니다.
팩토리 클래스를 가짐으로써 클래스 파일을 한 번만 포함하면됩니다. 필자가이 파일을 가지고 있지 않다면 파일을 사용할 때마다 클래스 파일을 포함시켜야합니다. 나중에 클래스 파일 이름을 업데이트해야한다면 factory 클래스 파일로만 업데이트하면됩니다.
팩토리 객체를 만드는 또 다른 이유는 DB 연결 수를 줄이는 것이 었습니다.
내가 별도의 파일로 각 클래스를 저장
공장 클래스
include_once('person.class.php');
include_once('tracking.class.php');
include_once('costAnalyzis.class.php');
include_once('activity.class.php');
class Factory {
function new_person_obj($id = NULL) { return new Person(Conn::get_conn(), $id); }
function new_tracking_obj($id = NULL) { return new Tracking(Conn::get_conn(), $id); }
function new_costAnalyzis_obj() { return new CostAnalyzis(Conn::get_conn()); }
function new_activity_obj() { return new Activity(Conn::get_conn()); }
}
연결 클래스
// I have this class in the same file as Factory class
// This creates DB connection and returns any error messages
class Conn {
private static $conn = NULL;
private function __construct() {}
private static function init() {
$conf = self::config();
try {
self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e) {
// We remove the username if we get [1045] Access denied
if (preg_match("/\b1045\b/i", $e->getMessage()))
echo "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)";
else
echo $e->getMessage();
}
}
public static function get_conn() {
if (!self::$conn) { self::init(); }
return self::$conn;
}
// I used to get login info from config file. Now I use Wordpress constants
private static function config() {
$conf = array();
$conf['user'] = DB_USER; //$config['db_user'];
$conf['pass'] = DB_PASSWORD; //$config['db_password'];
$conf['dsn'] = 'mysql:dbname='.DB_NAME.';host='.DB_HOST;
return $conf;
}
}
다른 클래스는
,369 객체
다음은 수업입니다. 데이터를 사용하는 곳입니다. 제 자신의 코드에서 비즈니스 계층과 데이터 개체 계층에서 프레젠테이션을 분리하는 3 계층 아키텍처를 사용하고 있습니다.
class Person extends PersonDAO {
function getPersonData($id) {
$result = parent::getPersonData($id);
// Here you can work with your data. If you do not need to handle data, just return result
return $result;
}
}
// I only have SQL queries in this class and I only return RAW results.
class PersonDAO {
// This variable is also available from you mother class Person
private $db;
// Constructor. It is automatically fired when calling the function.
// It must have the same name as the class - unless you define
// the constructor in your mother class.
// The &$db variable is the connection passed from the Factory class.
function PersonDAO (&$db) {
$this->db = &$db;
}
public function get_data($id) {
$sql ="SELECT a, b, c
FROM my_table
WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':id'=> $id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public function get_some_other_data() {
$sql ="SELECT a, b, c
FROM my_table_b";
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
다른 클래스에 대해서도 동일한 작업을 수행하십시오.
우리가 함께 하나 개의 파일, 공장 파일을 포함
공지 사항을 모든 퍼팅. 다른 모든 클래스 파일은 팩토리 클래스 파일에 포함됩니다. 내가 그것을 알 수있는 바와 같이
// Include factory file
include_once('factory.class.php');
//Create your factory object
$person = Factory::new_person_obj();
//Get person data
$data = $person->getPersonData('12');
// output data
print_r($data);
여기 왜 전역 정적 클래스 메서드를 사용하는지 이해하려고하지 않습니다. – hakre