PHP 및 PDONE을 사용하여 Mysql 데이터베이스 액세스
PHP 및 PDONE을 사용하여 Mysql 데이터베이스 액세스
PDONE은 성능과 무의존성을 두 가지 목표로 하는 라이브러리입니다.이 라이브러리는 5개의 클래스와 하나의 인터페이스로만 구성되어 있다.
https://github.com/EFTEC/PdoOne
이 라이브러리에는 데이터베이스를 사용하는 세 가지 방법이 포함되어 있다.
영수증 예시.
우리의 연습에서, 우리는 그것을 사용하여 영수증을 삽입하고 읽을 것이다.이 모델은 세 개의 테이블을 포함한다.
샘플 데이터베이스 만들기
ySQL에서 다음 스크립트를 실행합니다.
CREATE SCHEMA `example-pdo` ;
CREATE TABLE `customers` (
`IdCustomer` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(45) NULL,
PRIMARY KEY (`IdCustomer`));
CREATE TABLE `invoices` (
`IdInvoice` INT NOT NULL,
`Date` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`IdCustomer` INT NULL,
PRIMARY KEY (`IdInvoice`),
INDEX `invoices_fk1_idx` (`IdCustomer` ASC) VISIBLE,
CONSTRAINT `invoices_fk1`
FOREIGN KEY (`IdCustomer`)
REFERENCES `customers` (`IdCustomer`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE TABLE `invoice_detail` (
`IdInvoiceDetail` INT NOT NULL AUTO_INCREMENT,
`Product` VARCHAR(45) NULL,
`UnitPrice` DECIMAL(10,2) NULL,
`Quantity` INT NULL,
PRIMARY KEY (`IdInvoiceDetail`));
CREATE TABLE `invoice_details` (
`IdInvoiceDetail` INT NOT NULL AUTO_INCREMENT,
`IdInvoice` INT NULL,
`Product` VARCHAR(45) NULL,
`UnitPrice` DECIMAL(10,2) NULL,
`Quantity` INT NULL,
PRIMARY KEY (`IdInvoiceDetail`),
INDEX `invoice_detail_fk1_idx` (`IdInvoice` ASC) VISIBLE,
CONSTRAINT `invoice_detail_fk1`
FOREIGN KEY (`IdInvoice`)
REFERENCES `invoices` (`IdInvoice`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
데이터베이스에 연결
우선, 라이브러리를 설치해야 합니다. composer를 통해 다운로드하거나 설치할 수 있습니다. (composer는 eftec/PDONE이 필요합니다.)
//세 번째 방법에 대해 이 변수 글로벌은 $pdoOne이라고 불리거나 실례를 주입해야 하거나 pdoOne () 이라는 함수로 이 실례를 되돌려야 합니다.
$pdoOne=new PdoOne('mysql','127.0.0.1','root','abc.123','example-pdo'); // type of database, server, user, password, schema name.
$pdoOne->open(); // we will open the connection
$pdoOne->logLevel=3; // it shows all errors with arguments (it is for debug purpose)
방법 1: 원본 조회를 사용합니다.
example_simple.php
PDONE에서는 확장 PDO를 사용하여 데이터베이스에 직접 실행할 수 있는 원본 질의를 사용할 수 있습니다.이것은 우리 코드를 실행하는 가장 빠른 방식입니다. 따라서 속도를 원한다면 이상적입니다.PDO의 단순 포장기이기 때문입니다.
삽입 중
예를 들어, 고객을 삽입합니다.
$statement=$pdoOne->runRawQuery('insert into customers(name) values (?)',['John Simple'],false);
$statement->closeCursor(); // it is a pdostatement
$statement=null;
$idCustomer=$pdoOne->insert_id();
runRawQuery () 메서드에 매개변수를 전달하는 몇 가지 방법이 있습니다.runRawQuery()는 PdoStatement 또는 배열을 반환할 수 있습니다.기본적으로 배열을 되돌려주지만 PDO 문장을 얻을 수 있고 PDO를 확장하는 특수 기능을 사용할 수 있습니다.삽입된 다른 예제 (PDO 문 없음)
$pdoOne->runRawQuery('insert into customers(name) values (?)',['John Simple'],true);
$idCustomer=$pdoOne->insert_id(); // we get the identity.
다른 예 (명명된 매개변수 포함)$pdoOne->runRawQuery('insert into customers(name) values (:name)',['name'=>'John Simple'],true);
$idCustomer=$pdoOne->insert_id();
echo "added user $idCustomer";
표책
$customers=$pdoOne->runRawQuery('select * from customers where name=?',['John Simple']);
var_dump($customers);
그것은 값이 있는 관련 그룹을 되돌려줍니다.개별 객체 가져오기
$customers=$pdoOne->runRawQuery('select * from customers where idcustomer',[1]);
var_dump($customers); // [0=>['idcustomer'=>1,'name'=>'john']]
var_dump($customers[0]); // ['idcustomer'=>1,'name'=>'john']
전체 청구서 삽입
// invoice header
$invoice=['IdInvoice'=>1,'Date'=> PdoOne::dateSqlNow(true), 'IdCustomer'=>1];
$pdoOne->runRawQuery('insert into invoices(idinvoice,date,idcustomer) values(:IdInvoice,:Date,:IdCustomer)',$invoice);
// Creating the detail of the invoice
$invoiceDetail=[1,'Cocacola',1000,3];
$query='insert into invoice_details(idinvoice,product,unitprice,quantity) values (?,?,?,?)';
$pdoOne->runRawQuery($query, $invoiceDetail);
$invoiceDetail=[1,'Fanta',2000,5];
$query='insert into invoice_details(idinvoice,product,unitprice,quantity) values (?,?,?,?)';
$pdoOne->runRawQuery($query, $invoiceDetail);
메서드 2: 메서드 체인 사용
example_method_chains.php
PDONE은 또한 메소드 체인(fluent)을 사용할 수 있습니다.이런 방법도 기본이기 때문에 성능은 원시 조회에 가깝다.방법 체인은 여러 개의 체인 방법 중 하나로 작동하며, 항상 체인 방법의 한쪽으로 끝내야 합니다. (예를 들어 insert,toList,first,update 등)일반적으로 모든 방법을 순서대로 연결할 수 있지만, 체인의 끝은 반드시 체인의 끝에 있어야 한다.
코드의 실행은 항상 체인의 끝에 있다.
삽입 중
insert를 작성할 수 있는 많은 방법이 있습니다.이것은 그중의 하나다.
$idCustomer=$pdoOne
->from('customers')
->set(['name'=>'John Chain #1'])
->insert(); // $idcustomer gets the identity if any
게다가$idCustomer=$pdoOne->insert('customers',['name'=>'John Chain #2']); // $idcustomer gets the identity if any
표책
우리는 몇 가지 방법을 사용할 수 있다
$customers=$pdoOne->select('*')
->from('customers')
->toList(); // end of the chain, it returns an associative array with the values.
개별 객체 가져오기
일방통행도 가능합니다.이 라이브러리는 단일 값을 가져올 수 있습니다 (계수를 되돌려주는 데 사용됩니다)
$customer=$pdoOne->select('*')
->from('customers')
->where('idcustomer=?',[1])
->first();
첫 번째 질의를 반환합니다.쿼리가 값을 반환하지 않으면false를 반환합니다.쿼리가 여러 줄로 되돌아오면 첫 줄만 되돌아옵니다.전체 청구서 삽입
// invoice header
$invoice=['IdInvoice'=>1,'Date'=> PdoOne::dateSqlNow(true), 'IdCustomer'=>1];
$pdoOne->set($invoice)->from('invoices')->insert();
// Creating the detail of the invoice
$invoiceDetail=['IdInvoice'=>1,'Product'=>'Cocacola','UnitPrice'=>1000,'Quantity'=>3];
$pdoOne->set($invoiceDetail)->from('invoice_details')->insert();
$invoiceDetail=['IdInvoice'=>1,'Product'=>'Fanta','UnitPrice'=>5000,'Quantity'=>5];
$pdoOne->set($invoiceDetail)->from('invoice_details')->insert();
메서드 3: 저장소 클래스 사용
example_use_generated.php(어레이)
example_use_generated_object.php(객체)
이런 방법은 별도의 절차가 필요하다.새 클래스 그룹을 만들어야 합니다.이러한 새로운 종류는 미리 계산된 것이며 데이터베이스 모델에서 얻을 수 있다.비록 그것은 매우 빠르지만, 주로 대부분의 수치가 사전에 한 번 계산되기 때문이지만, 그것은 여전히 다른 방법보다 더 많이 한다.
클래스 만들기
example_method_generate.php
우리의 연습에서, 우리는customers, invoice_details, invoice 세 개의 표를 사용할 것이다.
표 고객의 경우 InvoiceDetailRepo 및 선택적 모델 클래스(InvoiceDetail) 두 가지 클래스를 생성해야 합니다.
$errors=$pdoOne->generateAllClasses(
[
'customers'=>['CustomerRepo','Customer'], // table => [repo class, model class]
'invoice_details'=>['InvoiceDetailRepo','InvoiceDetail'],
'invoices'=>['InvoiceRepo','Invoice']
]
,'BaseRepo' // it a common class
,['example\repo','example\model'] // namespaces of the repository class and model class.
,[__DIR__.'\repo',__DIR__.'\model']); // folders to where the repositories and model will be generated, they should exist.
$errors=$pdoOne->generateAllClasses(
[
'customers'=>'CustomerRepo', // table => repo class
'invoice_details'=>'InvoiceDetailRepo',
'invoices'=>'InvoiceRepo'
]
,'BaseRepo' // it a common class
,'example\repo' // namespaces of the repository class.
,__DIR__.'\repo'); // folders to where the repositories will be generated, they should exist.
만약 우리가 이 클래스를 실행한다면, 그것은 다음 파일을 생성할 것이다.📁 모델
📃 추상적인 고객.php//.
📃 손님php//우리 모델 (이 파일은 편집할 수 있습니다)
...
📁 되팔다
📃 추상적인 고객 보고.php//우리의repository 클래스, 이 파일은 편집할 수 없습니다. 바꿀 수 있기 때문입니다.
📃 고객 보고서.php//repository 클래스, 이 파일은 편집할 수 있습니다
📃 BaseRepo.php//모든 테이블의 일반적인 정보입니다.
...
삽입 중
우선, 우리는 두 가지 방식으로 대상을 만들 수 있다
만약 우리가 그룹을 사용하고 싶다면, 우리는 반드시 다음 값을 설정해야 한다
BaseRepo::$useModel=false; // we will use array instead of objects
배열 생성, BaseRepo: $useModel=false// using factory
$cus=CustomerRepo
::setRecursive('*')
::factory(['Name' => 'John Generated #1 (Array)']);
// using an array (the keys of the arrays must matches the columns of the table, including the case)
$cus=['Name' => 'John Generated #1 (Array)']; // correct
$cus=['name' => 'John Generated #1 (Array)']; // not correct (the column is called 'Name', not 'name')
또는 BaseRepo: $useModel=true 객체를 만듭니다.// using the constructor
$cus=new Customer(['Name' => 'John Generated #1 (Array)']);
// with empty constructor
$cus=new Customer();
$cus->Name='John Generated #1 (Array)';
우리는 아래의 내용을 삽입할 수 있다$identity=CustomerRepo::insert($cus);
이 방법은 다음 조작을 실행한다.표책
이것은 방법 체인과 유사하지만 약간의 차이가 있다.
$r=CustomerRepo::where('IdCustomer',[1])::toList(); // select IdCustomer,Name from customers where IdCustomer=1
개별 객체 가져오기
$invoice=CustomerRepo::where('IdCustomer',[1])::first();
전체 청구서 삽입
배열 사용
// header
$invoice=InvoiceRepo::setRecursive('*')::factory(['IdInvoice'=>1,'Date'=> PdoOne::dateSqlNow(true), 'IdCustomer'=>1]);
// InvoiceDetailRepo: IdInvoice islinked automatically, and IdInvoiceDetail is identity.
$invoice['_invoice_details']=[
InvoiceDetailRepo::factory(['Product' => 'Cocacola','UnitPrice' => 1000,'Quantity' => 3]),
InvoiceDetailRepo::factory(['Product' => 'Fanta','UnitPrice' => 5000,'Quantity' => 2])
];
InvoiceRepo::setRecursive('_invoice_details')::insert($invoice);
또는 객체 사용// header
$invoice=new Invoice();
$invoice->IdInvoice=1;
$invoice->Date=PdoOne::dateSqlNow(true);
$invoice->IdCustomer=1;
// InvoiceDetailRepo: IdInvoice islinked automatically, and IdInvoiceDetail is identity.
$invoice->_invoice_details=[
new InvoiceDetail(['Product' => 'Cocacola','UnitPrice' => 1000,'Quantity' => 3]),
new InvoiceDetail(['Product' => 'Fanta','UnitPrice' => 5000,'Quantity' => 2])
];
InvoiceRepo::setRecursive('_invoice_details')::insert($invoice);
setRecursive() 메서드는 무엇입니까?하면, 만약, 만약...
영수증 환매::삽입($invoice);
그런 다음 첫 번째 표(송장)를 고려한 값을 삽입합니다
송장에 (IdInvoice, Date, IdCustomer) 값 삽입(...);
그러나 우리는 영수증에 대한 상세한 정보를 삽입하지 않았다.
반대로
InvoiceRepo::setRecursive('*'):삽입($invoice);
다음 삽입이 진행됩니다.
insert into invoices(..) values (..);
insert into invoice_details(..) values (..);
insert into invoice_details(..) values (..);
insert into customer(..) values (..); -- however we don't want to insert the customer.
따라서 정확한 귀착성은InvoiceRepo::setRecursive('\u invoice\u details'):삽입($invoice);
클래스 저장소를 생성할 때, 라이브러리는 모든 외부 키를 수집합니다.외부 키를 통해 관계를 생성할 수 있다.이 경우 다음 관계가 생성됩니다.
ONETOMANY invoices->invoice\u details(\u invoice\u details라는 필드 사용)
복수 청구서 -> 고객("고객"필드 사용)
// examples:
// invoices->customers
InvoiceRepo::setRecursive(['_customers']);
// invoice->customers and invoice->invoice_details
InvoiceRepo::setRecursive(['_customers','_invoice_details']);
// invoice->customers , invoice->invoice_details and invoice_details->invoices
InvoiceRepo::setRecursive(['_customers','_invoice_details/_invoices']);
메모를 끝냅니다.
$invoices=InvoiceRepo::toList(); // select IdInvoice,Date,IdCustomer from invoices
$invoices=InvoiceRepo::base()->runRawQuery('select * from invoices'); // select * from invoices
$invoices=InvoiceRepo::base()->select('*')->from('invoices')->toList(); // select * from invoices
소스 코드
https://github.com/escuelainformatica/example-pdoone
Reference
이 문제에 관하여(PHP 및 PDONE을 사용하여 Mysql 데이터베이스 액세스), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jorgecc/accessing-a-mysql-database-using-php-and-pdoone-fjg텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)