Sangat disarankan agar Anda menggunakan flightphp/active-record daripada perpustakaan ini. Tidak ada pengembangan lebih lanjut yang akan dilakukan terhadap perpustakaan ini, tetapi perpustakaan ini berfungsi seperti sekarang.
super model adalah kelas php tipe ORM yang sangat sederhana untuk berinteraksi dengan tabel dalam database dengan mudah tanpa menulis banyak kode SQL di semua tempat.
Untuk membuktikannya, berikut baris kodenya...
$ cloc src/
1 text file.
1 unique file.
0 files ignored.
github.com/AlDanial/cloc v 1.74 T=0.01 s (71.8 files/s, 48768.5 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
PHP 1 86 246 347
-------------------------------------------------------------------------------
Ini ditulis dengan mempertimbangkan kinerja. Jadi meskipun hal ini tidak akan memenuhi setiap persyaratan dalam setiap proyek yang pernah dibangun, hal ini akan berhasil dalam sebagian besar kasus, dan melakukan pekerjaan yang hebat juga!
Memulai dengan super model itu mudah, cukup perluas kelas super model dan tentukan nama tabel. Itu saja.
<?php
use n0nag0n Super_Model ;
class User extends Super_Model {
protected $ table = ' users ' ;
}
Sekarang bagaimana dengan beberapa contoh sederhana tentang cara kerjanya?
Pertama, mari kita asumsikan tabel berikut:
Table: users
---------------------------------------------------------
| id | email | company_id |
| 1 | [email protected] | 50 |
| 2 | [email protected] | 61 |
| 3 | [email protected] | 61 |
---------------------------------------------------------
<?php
// somefile.php
$ pdo = new PDO ( ' sqlite::memory: ' , '' , '' , [ PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC ]);
$ User = new User ( $ pdo );
// WHERE company_id = 50
$ users = $ User -> getAllBycompany_id ( 50 );
// same as above
$ users = $ User -> getAll ([ ' company_id ' => 50 ]);
Mudah sekali, perasan lemon kan?
getBy*(mixed $value): array [result]
Ini adalah metode yang mengembalikan satu baris dari nilai yang ditentukan. Bagian *
dari metode ini mengacu pada bidang dalam database. Nama field peka huruf besar-kecil terhadap nama field apa pun yang ada di tabel database Anda.
// get by the id field on the users table
$ User -> getByid ( 3 );
/*
[
'id' => 3,
'email' => '[email protected]',
'company_id' => 61
]
*/
$ User -> getBycompany_id ( 61 );
/*
// it only will pull the first row, not all rows
[
'id' => 2,
'email' => '[email protected]',
'company_id' => 61
]
*/
getAllBy*(mixed $value): array [ [result], [result] ]
Ini adalah filter pintasan untuk mengembalikan semua baris dengan nilai tertentu. Bagian *
dari metode ini mengacu pada bidang dalam database. Nama field peka huruf besar-kecil terhadap nama field apa pun yang ada di tabel database Anda.
// this is pointless, but will still work
$ User -> getAllByid ( 3 );
/*
[
[
'id' => 3,
'email' => '[email protected]',
'company_id' => 61
]
]
*/
$ User -> getAllBycompany_id ( 61 );
/*
[
[
'id' => 2,
'email' => '[email protected]',
'company_id' => 61
],
[
'id' => 3,
'email' => '[email protected]',
'company_id' => 61
]
]
*/
getAll(array $filters, bool $return_one_row = false): array [ [result], [result] ] or [result]
Ini adalah filter tempat Anda dapat menambahkan banyak penyesuaian untuk memfilter data dari tabel Anda. Ada beberapa kunci unik yang perlu diperhatikan dan beberapa operator untuk membantu Anda mengambil data spesifik Anda.
// Full example
$ filters = [
//
// arguments in the WHERE statement
//
' some_field ' => 5 , // some_field = ?
' some_field-= ' => 5 , // some_field = ?
' another_field ' => ' IS NULL ' , // some_field IS NULL
' another_field ' => ' IS NOT NULL ' , // some_field IS NOT NULL
' another_field-> ' => ' Apple ' , // another_field > ?
' another_field->= ' => ' Apple ' , // another_field >= ?
' another_field-< ' => ' Apple ' , // another_field < ?
' another_field-<= ' => ' Apple ' , // another_field <= ?
' another_field-!= ' => ' Apple ' , // another_field != ?
' another_field-<> ' => ' Apple ' , // another_field <> ?
' another_field-LIKE ' => ' Ap%ple ' , // another_field LIKE ?
' another_field-NOT LIKE ' => ' Apple% ' , // another_field NOT LIKE ?
' another_field-IN ' => [ ' Apple ' , ' Banana ' , ' Peach ' ], // another_field IN(??) double question mark gets parsed as array
' another_field-NOT IN ' => [ ' Apple ' , ' Banana ' , ' Peach ' ], // another_field NOT IN(??) double question mark gets parsed as array
// If you need some custom action
' another_field-RAW-> DATE_SUB(?, INTERVAL 1 DAY) ' => ' 1980-01-01 ' , // another_field > DATE_SUB(?, INTERVAL 1 DAY)
//
// Other parts of the query
//
// choose what columns you want to select
' select_fields ' => ' id, first_name ' ,
// Get any joins
' joins ' => [ ' LEFT JOIN companies ON companies.id = users.company_id ' ],
// Group by
' group_by ' => ' company_id ' ,
// having
' having ' => ' count > 5 ' ,
// order by
' order_by ' => ' id DESC ' ,
// limit
' limit ' => 15 ,
// offset
' offset ' => 10000 ,
];
$ users = $ User -> getAll ( $ filters );
Ada juga beberapa opsi konfigurasi dasar dengan properti model.
Jika Anda memiliki model yang Anda tahu akan selalu mengembalikan kumpulan hasil kecil dan ingin dapat mengkueri seluruh tabel, atur properti ini. Jika tidak, ini adalah perlindungan sehingga jika tidak ada parameter sql yang diberikan, Anda tidak akan mengambil kembali seluruh rangkaian hasil (yang dapat menyebabkan crash dan membakar banyak hal).
use n0nag0n Super_Model ;
class User extends Super_Model {
protected $ table = ' users ' ;
protected $ disallow_wide_open_queries = false ;
}
create(array $data): int [insert id]
Ini akan membuat satu baris pada tabel, tetapi jika Anda menyediakan array multidimensi, ini akan menyisipkan beberapa baris. Kunci utama id
diasumsikan.
$ User -> create ([ ' email ' => ' [email protected] ' , ' company_id ' => 55 ]);
// returns 4
$ User -> create ([ [ ' email ' => ' [email protected] ' , ' company_id ' => 55 ], [ ' email ' => ' [email protected] ' , ' company_id ' => 56 ] ]);
// returns 6, only the last id will be returned
update(array $data, string $update_field = 'id'): int (number of rows updated)
Ini akan membuat satu baris pada tabel, tetapi jika Anda menyediakan array multidimensi, ini akan menyisipkan beberapa baris. Kunci utama id
diasumsikan.
$ User -> update ([ ' id ' => 1 , ' email ' => ' [email protected] ' ]);
// returns 1 and will only update the email field
$ User -> update ([ ' email ' => ' [email protected] ' , ' company_id ' => 61 ], ' email ' );
// returns 1
$ User -> update ([ ' company_id ' => 61 , ' email ' => ' [email protected] ' ], ' company_id ' );
// returns 3, not really logical, but it would update all the emails
Bagaimana jika Anda menginginkan cara otomatis untuk mengubah hasil Anda jika tanda tertentu diaktifkan? Mudah sekali. Ada metode bernama processResult()
yang akan menjalankan setiap hasil yang Anda tarik kembali. Anda memasukkan filter khusus untuk metode ini ke dalam kunci $filters['processResults']
.
<?php
use n0nag0n Super_Model ;
class User extends Super_Model {
protected $ table = ' users ' ;
public processResult (array $ process_filters , array $ result ): array {
// add some trigger here and do whatever checks you need
if( isset ( $ process_filters ['set_full_name']) && $ process_filters ['set_full_name'] === true && !empty( $ result ['first_name']) && !empty( $ result ['last_name'])) {
$ result ['full_name'] = $ result [ ' first_name ' ]. ' ' . $ result [ ' last_name ' ];
}
return $ result ;
}
}
// later on in some other file.
$ User = new User ( $ pdo );
// setting the processResults filter here is the key to connecting the getAll statement with your processResult method
$ users = $ User -> getAll ([ ' company_id ' => 51 , ' processResults ' => [ ' set_full_name ' => true ] ]);
echo $ users [ 0 ][ ' full_name ' ]; // Bob Smith
Bagaimana jika Anda perlu melakukan kueri SQL rumit dan gila yang tidak termasuk dalam bidang kelas ini atau filter getAll()
?
Ingatlah bahwa inti dari kelas ini BUKAN untuk memenuhi setiap persyaratan dari setiap proyek yang pernah atau akan ada, tetapi ini akan membawa Anda 90% ke sana. Oleh karena itu, ada cara sederhana untuk menjalankan pertanyaan di atas. Cukup gunakan RAW SQL untuk Anda.
<?php
use n0nag0n Super_Model ;
class User extends Super_Model {
protected $ table = ' users ' ;
public function processCrazyKukooQuery ( /* add whatever required fields you need */ ): array {
$ db = $ this -> getDbConnection ();
// shamelessly ripped from StackOverflow
$ statement = $ db -> prepare ( " SELECT
DISTINCT
t.id,
t.tag,
c.title AS Category
FROM
tags2Articles t2a
INNER JOIN tags t ON t.id = t2a.idTag
INNER JOIN categories c ON t.tagCategory = c.id
INNER JOIN (
SELECT
a.id
FROM
articles AS a
JOIN tags2articles AS ta ON a.id=ta.idArticle
JOIN tags AS tsub ON ta.idTag=tsub.id
WHERE
tsub.id IN (12,13,16)
GROUP BY a.id
HAVING COUNT(DISTINCT tsub.id)=3
) asub ON t2a.idArticle = asub.id " );
$ statement -> execute ();
return $ statement -> fetchAll ();
}
}
Cukup jalankan composer test
untuk menjalankan phpunit
dan phpstan
. Saat ini cakupannya 100% dan di sanalah saya ingin mempertahankannya.
Catatan tentang cakupan 100%: Meskipun kode mungkin memiliki cakupan 100%, cakupan sebenarnya berbeda. Tujuannya adalah untuk menguji banyak skenario berbeda terhadap kode untuk memikirkan kode tersebut dan mengantisipasi hasil yang tidak diharapkan. Saya mengkodekan ke cakupan "nyata", bukan cakupan "apakah kodenya berjalan".