Corso yii #04 - il database

Post on 06-Dec-2014

638 views 0 download

description

 

Transcript of Corso yii #04 - il database

1

Lavorare con i database

2

Question time

3

Introduzione

4

Yii offre un potente supporto per la

programmazione con database

5

Il Data Access Object di Yii, è costruisto

sull’estensione PHP Data Object (PDO) di

PHP.

6

Possiamo accedere, con DAO, a tutti i DBMS che supportano PDO.

7

Mai più SQL...

più o meno

8

Query Builder&&

Active Record

9

Query Builder

10

Yii Query Builder:“queries object-

oriented”

11

SQL injection

12

Active Record

13

Approccio Object-Relational Mapping

(ORM)

14

Classe PHP==

Tabella

15

Oggetto PHP==

Record della Tabella

16

Question time

17

Database Access Object

18

Introduzione al DAO

19

API per accedere ai dati memorizzati nel DBMS

20

Basato su PDO, un’estensione che

fornisce un accesso unico a diversi DBMS

21

MySQL

22

PostgreSQL

23

SQLlite

24

Le classi del DAO

•CDbConnection: connessione al database

•CDbCommands: query SQL

•CDbDataReader: record di un result set

•CDbTransaction: transazione

25

Connessione al database

26

$conn = new CDbConnection($dsn, // Data Source Name$username,$password

);

$conn->active = true;

$conn->active = false;

27

DSN (Data Source Name)

28

“nome driver PDO;sintassi della connessione”

29

MySQL: mysql:host=localhost;dbname=testd

b

30

Oracle: oci:dbname=//localhost:1521/testdb

31

array( 'components'=>array( 'mysql'=>array( 'class'=>'CDbConnection', 'connectionString'=>'mysql:host=localhost;dbname=testdb', 'username'=>'root', 'password'=>'root' ), ),)

32

array( 'components'=>array( 'oci'=>array( 'class'=>'CDbConnection', 'connectionString'=>'oci:dbname=//localhost:1521/testdb', 'username'=>'root', 'password'=>'root' ), ),)

33

Yii::app()->mysql

34

Yii::app()->oci

35

Eseguire query SQL

36

Le query si eseguono usando:

CDbCommand::createCom

mand();

37

$connessione = Yii::app()->mysql;$connessione = new

CDbConnection($dsn, $u, $p);

$sql = ‘select * from utenti’;$comando = $connessione-

>createcommand($sql);

38

execute()

INSERT, UPDATE, DELETE

39

query() // CDbDataReader

SELECT

40

$rows = $command->queryAll();

restituisce tutti i records

41

$rows = $command->queryRow();

restituisce il primo record

42

Fetching dei risultati

43

query() e queryXXX()

restituiscono un CDbDataReader

44

$dataReader = $command->query();foreach($dataReader as $read) { // ...}

45

query() // restituisce tutti i dati

queryXXX() // restituiscono il primo record

46

Transazioni

47

CDbTransaction

48

$t = $conn->beginTransaction();

try {$conn->createcommand($sql)-

>execute();$conn->createcommand($sql)-

>execute();$conn->createcommand($sql)-

>execute();$t->commit();

} catch(Exception $e) {$t->rollback();

}

49

Bind dei parametri

50

SQL injection

51

$sql = ‘insert into utenti (username, email) values (:username, :email)’;

$command = $connessione->createCommand($sql);$command->bindParam(‘:username’, $username, PDO::PARAM_STR);$command->bindParam(‘:email’, $email, PDO::PARAM_STR);

$command->execute();

52

$sql = ‘select username, email from utenti’;

$dataReader = $connessione->createCommand($sql)->query();

$dataReader->bindColumn(1, $username);$dataReader->bindColumn(2, $email);

while ($dataReader->read() !== false) {echo $username;echo $email;

}

53

Prefisso delle tabelle

54

Se si usano più applicazioni con lo stesso database

55

ogni applicazione può avere un proprio

prefisso

56

yii_ potrebbe essere il prefisso della nostra

app

57

phpbb_ il prefisso del nostro forum

58

wp_ il prefisso del blog wordpress

59

e così via ...

60

CDbConnection::tablePrefix

contiene il prefisso della tabella

61

Nelle query sql possiamo usare {{table_name}}

62

yii_user ?select * from yii_user

select * from {{user}}

63

Question time

64

Query Builder

65

Introduzione al Query Builder

66

Modo object-oriented di scrivere query SQL

67

Assembla parti di SQL per renderle eseguibili

nel DAO di Yii

68

$user = Yii::app()->db->createCommand()

->select('username, email')->from('utenti u')->join('profili p',

'u.id=p.user_id')->where('id=:id',

array(':id'=>$id))->queryRow();

69

Con il QB è possibile comporre query

complesse

70

Gestisce automaticamente il quoting dei nomi di

tabella e dei campi per prevenire confrlitti

71

SQL injection

72

Ha un buon livello di astrazione che semplifica la

migrazione tra i vari DBMS

73

Preparazione del QB

74

$command = Yii::app()->mysql->createCommand();

75

select()selectDistinct()

76

from()

77

where()andWhere()orWhere()

78

join()leftJoin()

rightJoin()crossJoin()

naturalJoin()

79

group()having()order()limit()offset()union()

80

$user = Yii::app()->db->createCommand()

->union(‘select * from {{tabella}}’)

->queryRow();

81

$users = Yii::app()->db->createCommand() ->select('*') ->from('tbl_user') ->queryAll();

82

$sql = Yii::app()->db->createCommand() ->select('*') ->from('tbl_user') ->text;

83

$command = Yii::app()->db->createCommand();$users = $command->select('*')->from('tbl_users')->queryAll();

$command->reset();$posts = $command->select('*')->from('tbl_posts')->queryAll();

84

Manipolare i dati

85

insert()update()delete()

86

$command->insert('utenti', array( 'nome'=>'Simone', 'email'=>'sensorario@gmail.com',));

87

$command->update('utenti', array( 'nome'=>'Fabio',), 'id=:id', array(':id'=>1));

88

$command->delete('utenti', 'id=:id', array(':id'=>1));

89

Alterare lo schema del database

90

createTable()renameTable()

dropTable()truncateTable()

91

addColumn()renameColumn()

alterColumn()dropColumn()

92

createIndex()dropIndex()

93

Abstract Data Types•pk

•text

•string

•integer

•float

•decimal

•datetime

•timestamp

•time

•date

•binary

•boolean

•money

94

Question time

95

Active Record

96

Transazioni con Active Record

97

$model=Post::model();$transaction=$model->dbConnection->beginTransaction();try{ $post=$model->findByPk(10); $post->title='new post title'; $post->save(); $transaction->commit();}catch(Exception $e){ $transaction->rollback();}

98

Scopes

99

$post = Post::model()->findAll(array( 'order'=>'create_time DESC',

'limit'=>5, ));

100

class Post extends CActiveRecord{ public function scopes() { return array( 'recenti'=>array( 'order'=>'create_time DESC', 'limit'=>5, ), 'ultimo'=>array( 'order'=>'create_time DESC', 'limit'=>1, ), ); }}

$postRecenti = Post::model()->recenti()->findAll();

$postRecenti = Post::model()->ultimo()->findAll();

101

public static funtion getSomeValues ($campo = 33) {

return Post::model()->findAll(array( ‘condition’ => ‘campo=:campo’, ‘params’ => array( ‘:campo’ => $campo ) ));}

102

class Post extends CActiveRecord{ public function recenti($limit = 3) { $this->getDbCriteria()->mergeWidth(array( ‘order’ => ‘create_time DESC’, ‘limit’ => $limit )); return $this; }}

$postRecenti = Post::model()->recenti(4)->findAll();

103

Relazioni

104

Per non usare il lazy loading

$post = Post::model()->with(‘author’, ‘tags’)->findAll();

105

$posts=Post::model()-

>with('comments:recently:approved')->findAll();

$posts=Post::model()->findAll(array( 'with'=>array( 'comments'=>array( 'scopes'=>array('recently','approved') ), ),));

106

class User extends CActiveRecord{ public function relations() { return array( 'posts'=>array(self::HAS_MANY, 'Post', 'author_id', 'with'=>array( 'comments'=>array( 'scopes'=>'approved' ), ), ), ); }}

107

Question time

108

Database Migration

109

Marco aggiunge una tabella ed il codice ed i modelli che ne fanno

uso.

110

Marco ha aggiunto la tabella con una

migrazione e committa sul repository

111

Giuseppe scarica il codice sorgente e

langia le migrations

112

Giuseppe, senza sapere che cosa ha fatto

Marco, ha il database aggiornato.

113

Lanciando le migrazioni in produzione,

possiamo aggiornare lo schema del DB

114

Senza fare interventi MANUALMENTE

115

class m999999_999999_creo_una_tabella extends CDbMigration{ public function up() { $this->createTable('una_tabella', array( 'id' => 'pk', 'stringa' => 'string NOT NULL', 'testo' => 'text', )); } public function down() { $this->dropTable('una_tabella'); }}

116

Question time

117

Fine