SlideShare ist ein Scribd-Unternehmen logo
1 von 117
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
più o meno
più o meno
8
Query Builder
&&
Active Record
Active Record
Active Record
9
Query Builder
10
Yii Query Builder:
“queries object-oriented”
“queries object-oriented”
11
SQL injection
12
Active Record
13
Approccio Object-Relational
Mapping (ORM)
14
Classe PHP
==
Tabella
Tabella
Tabella
15
Oggetto PHP
==
Record della Tabella
Record della Tabella
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
PostreSQL
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;
$conn->active = false;
$conn->active = false;
$conn->active = false;
$conn->active = false;
$conn->active = false;
$conn->active = false;
$conn->active = false;
$conn->active = false;
27
DSN (Data Source Name)
28
“nome driver PDO;sintassi della connessione”
29
MySQL: mysql:host=localhost;dbname=testdb
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::createCommand();
CDbCommand::createCommand();
37
$connessione = Yii::app()->mysql;
$connessione = new CDbConnection($dsn, $u, $p);
$sql = ‘select * from utenti’;
$comando = $connessione->createcommand($sql);
$comando = $connessione->createcommand($sql);
$comando = $connessione->createcommand($sql);
$comando = $connessione->createcommand($sql);
$comando = $connessione->createcommand($sql);
38
execute()
INSERT, UPDATE, DELETE
INSERT, UPDATE, DELETE
INSERT, UPDATE, DELETE
39
query() // CDbDataReader
SELECT
SELECT
SELECT
40
$rows = $command->queryAll();
restituisce tutti i records
restituisce tutti i records
restituisce tutti i records
41
$rows = $command->queryRow();
restituisce il primo record
restituisce il primo record
restituisce il primo record
42
Fetching dei risultati
43
query() e queryXXX()
restituiscono un CDbDataReader
restituiscono un CDbDataReader
restituiscono un CDbDataReader
44
$dataReader = $command->query();
foreach($dataReader as $read) {
// ...
}
}
}
}
45
query() // restituisce tutti i dati
queryXXX() // restituiscono il primo record
queryXXX() // restituiscono il primo record
queryXXX() // restituiscono il primo record
46
Transazioni
47
CDbTransaction
48
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();
$command->execute();
$command->execute();
$command->execute();
$command->execute();
$command->execute();
$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
contiene il prefisso della
tabella
contiene il prefisso della
tabella
61
Nelle query sql possiamo
usare {{table_name}}
62
yii_user ?
select * from yii_user
select * from {{user}}
select * from {{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();
->queryRow();
->queryRow();
->queryRow();
->queryRow();
->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()
selectDistinct()
76
from()
77
where()
andWhere()
orWhere()
orWhere()
orWhere()
78
join()
leftJoin()
rightJoin()
crossJoin()
naturalJoin()
naturalJoin()
naturalJoin()
naturalJoin()
79
having()
order()
limit()
offset()
union()
union()
union()
union()
80
$user = Yii::app()->db->createCommand()
->union(‘select * from {{tabella}}’)
->queryRow();
->queryRow();
->queryRow();
81
$users = Yii::app()->db->createCommand()
->select('*')
->from('tbl_user')
->queryAll();
->queryAll();
->queryAll();
->queryAll();
82
$sql = Yii::app()->db-
>createCommand()
->select('*')
->from('tbl_user')
->text;
->text;
->text;
->text;
83
$command = Yii::app()->db->createCommand();
$users = $command->select('*')->from('tbl_users')->queryAll();
$command->reset();
$posts = $command->select('*')->from('tbl_posts')->queryAll();
$posts = $command->select('*')->from('tbl_posts')->queryAll();
$posts = $command->select('*')->from('tbl_posts')->queryAll();
$posts = $command->select('*')->from('tbl_posts')->queryAll();
$posts = $command->select('*')->from('tbl_posts')->queryAll();
84
Manipolare i dati
85
insert()
update()
delete()
delete()
delete()
86
$command->insert('utenti', array(
'nome'=>'Simone',
'email'=>'sensorario@gmail.com',
));
));
));
));
87
$command->update('utenti', array(
'nome'=>'Fabio',
), 'id=:id', array(':id'=>1));
), 'id=:id', array(':id'=>1));
), '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()
truncateTable()
truncateTable()
truncateTable()
91
addColumn()
renameColumn()
alterColumn()
dropColumn()
dropColumn()
dropColumn()
dropColumn()
92
createIndex()
dropIndex()
dropIndex()
93
Abstract Data Types
• pk
• text
• string
• integer
• float
• decimal
• datetime
• timestamp
94
Question time
95
Active Record
96
Transazioni con Active
Record
97
$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
$postRecenti = Post::model()->ultimo()->findAll();
101
{
return Post::model()->findAll(array(
‘condition’ => ‘campo=:campo’,
‘params’ => array(
‘:campo’ => $campo
)
));
}
}
}
}
}
}
}
102
$postRecenti = Post::model()->recenti(4)->findAll();
103
Relazioni
104
Per non usare il lazy loading
$post = Post::model()
->with(‘author’, ‘tags’)
->findAll();
->findAll();
->findAll();
->findAll();
->findAll();
105
$posts=Post::model()->findAll(array(
'with'=>array(
'comments'=>array(
'scopes'=>array('recently','approved')
),
),
));
));
));
));
));
));
106
'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
'stringa' => 'string NOT NULL',
'testo' => 'text',
));
}
public function down()
{
$this->dropTable('una_tabella');
}
}
}
}
}
}
}
}
}
}
116
Question time
117
Fine

Weitere ähnliche Inhalte

Ähnlich wie Corso yii #04 - il database

Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...Fulvio Corno
 
CakePhp Linux Day Torino '09
CakePhp Linux Day Torino '09CakePhp Linux Day Torino '09
CakePhp Linux Day Torino '09Francesco Ronchi
 
Giovambattista Fazioli, 10 more things
Giovambattista Fazioli, 10 more thingsGiovambattista Fazioli, 10 more things
Giovambattista Fazioli, 10 more thingsKnowCamp
 
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente Andrea Dottor
 
Presentazione django reminiscence
Presentazione django reminiscencePresentazione django reminiscence
Presentazione django reminiscenceAndrea Gottardi
 
Simple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computingSimple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computingFrancesca1980
 
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANODrupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANODrupalDay
 
Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8Wellnet srl
 
Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8Eugenio Minardi
 
Polyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDB
Polyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDBPolyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDB
Polyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDBSteve Maraspin
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBStefano Dindo
 
Portofino 4: Creare Webapp da Database Esistenti in 30 Secondi
Portofino 4: Creare Webapp da Database Esistenti in 30 SecondiPortofino 4: Creare Webapp da Database Esistenti in 30 Secondi
Portofino 4: Creare Webapp da Database Esistenti in 30 SecondiPaolo Predonzani
 
Power BI: Introduzione ai dataflow e alla preparazione dei dati self-service
Power BI: Introduzione ai dataflow e alla preparazione dei dati self-servicePower BI: Introduzione ai dataflow e alla preparazione dei dati self-service
Power BI: Introduzione ai dataflow e alla preparazione dei dati self-serviceMarco Pozzan
 
Self hosted Services with .NET OWin
Self hosted Services with .NET OWinSelf hosted Services with .NET OWin
Self hosted Services with .NET OWinNicolò Carandini
 
Py a6 python-database
Py a6 python-databasePy a6 python-database
Py a6 python-databaseMajong DevJfu
 
Entity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernateEntity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernateManuel Scapolan
 

Ähnlich wie Corso yii #04 - il database (20)

Data flow
Data flowData flow
Data flow
 
Laravel Framework PHP
Laravel Framework PHPLaravel Framework PHP
Laravel Framework PHP
 
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
 
Corso Java 2 - AVANZATO
Corso Java 2 - AVANZATOCorso Java 2 - AVANZATO
Corso Java 2 - AVANZATO
 
CakePhp Linux Day Torino '09
CakePhp Linux Day Torino '09CakePhp Linux Day Torino '09
CakePhp Linux Day Torino '09
 
Giovambattista Fazioli, 10 more things
Giovambattista Fazioli, 10 more thingsGiovambattista Fazioli, 10 more things
Giovambattista Fazioli, 10 more things
 
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
 
Presentazione django reminiscence
Presentazione django reminiscencePresentazione django reminiscence
Presentazione django reminiscence
 
Simple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computingSimple Cloud API: accesso semplificato al cloud computing
Simple Cloud API: accesso semplificato al cloud computing
 
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANODrupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANO
 
Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8
 
Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8Come sfruttare tutte le potenzialità di Symfony in Drupal 8
Come sfruttare tutte le potenzialità di Symfony in Drupal 8
 
Polyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDB
Polyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDBPolyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDB
Polyglot Persistance con PostgreSQL, CouchDB, MongoDB, Redis e OrientDB
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDB
 
Portofino 4: Creare Webapp da Database Esistenti in 30 Secondi
Portofino 4: Creare Webapp da Database Esistenti in 30 SecondiPortofino 4: Creare Webapp da Database Esistenti in 30 Secondi
Portofino 4: Creare Webapp da Database Esistenti in 30 Secondi
 
Power bi
Power biPower bi
Power bi
 
Power BI: Introduzione ai dataflow e alla preparazione dei dati self-service
Power BI: Introduzione ai dataflow e alla preparazione dei dati self-servicePower BI: Introduzione ai dataflow e alla preparazione dei dati self-service
Power BI: Introduzione ai dataflow e alla preparazione dei dati self-service
 
Self hosted Services with .NET OWin
Self hosted Services with .NET OWinSelf hosted Services with .NET OWin
Self hosted Services with .NET OWin
 
Py a6 python-database
Py a6 python-databasePy a6 python-database
Py a6 python-database
 
Entity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernateEntity Framework 4.0 vs NHibernate
Entity Framework 4.0 vs NHibernate
 

Mehr von Simone Gentili

test driven development with phpunit
test driven development with phpunittest driven development with phpunit
test driven development with phpunitSimone Gentili
 
Back end User Group / Golang Intro
Back end User Group / Golang IntroBack end User Group / Golang Intro
Back end User Group / Golang IntroSimone Gentili
 
DevRomagna / Golang Intro
DevRomagna / Golang IntroDevRomagna / Golang Intro
DevRomagna / Golang IntroSimone Gentili
 
Javascript Camp - Listener Per Eventi
Javascript Camp - Listener Per EventiJavascript Camp - Listener Per Eventi
Javascript Camp - Listener Per EventiSimone Gentili
 

Mehr von Simone Gentili (6)

test driven development with phpunit
test driven development with phpunittest driven development with phpunit
test driven development with phpunit
 
Back end User Group / Golang Intro
Back end User Group / Golang IntroBack end User Group / Golang Intro
Back end User Group / Golang Intro
 
Laravel Day / Deploy
Laravel Day / DeployLaravel Day / Deploy
Laravel Day / Deploy
 
DevRomagna / Golang Intro
DevRomagna / Golang IntroDevRomagna / Golang Intro
DevRomagna / Golang Intro
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Javascript Camp - Listener Per Eventi
Javascript Camp - Listener Per EventiJavascript Camp - Listener Per Eventi
Javascript Camp - Listener Per Eventi
 

Corso yii #04 - il database