~desarrollokumbia/kumbia/ActiveRecord

« back to all changes in this revision

Viewing changes to active_record2/active_record2.php

  • Committer: Emilio Silveira
  • Date: 2010-07-30 03:22:48 UTC
  • Revision ID: emilio.rst@gmail.com-20100730032248-9n4vnvcist5rjze1
Cambios multiples.

Implementado en ActiveRecord create y update con validaciones y 
disparadores before y after

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
 * @copyright  Copyright (c) 2005-2009 Kumbia Team (http://www.kumbiaphp.com)
20
20
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
21
21
 */
22
 
/**
23
 
 * @see KumbiaModel
24
 
 */
 
22
 
 
23
// @see KumbiaModel
25
24
require_once CORE_PATH . 'libs/ActiveRecord/active_record2/kumbia_model.php';
26
 
/**
27
 
 * @see ResultSet
28
 
 */
29
 
require_once CORE_PATH . 'libs/ActiveRecord/db_pool/result_set.php';
 
25
 
30
26
/**
31
27
 * ActiveRecord Clase para el Mapeo Objeto Relacional
32
28
 *
41
37
 */
42
38
class ActiveRecord2 extends KumbiaModel implements Iterator
43
39
{
 
40
        /**
 
41
         * Obtener datos cargados en objeto del Modelo
 
42
         * 
 
43
         */
 
44
        const FETCH_MODEL = 'model';
 
45
        
 
46
        /**
 
47
         * Obtener datos cargados en objeto
 
48
         * 
 
49
         */
 
50
        const FETCH_OBJ = 'obj';
 
51
        
 
52
        /**
 
53
         * Obtener datos cargados en array
 
54
         * 
 
55
         */
 
56
        const FETCH_ARRAY = 'array';
 
57
                
44
58
    /**
45
59
     * Conexion a base datos que se utilizara
46
60
     *
47
61
     * @var strings
48
 
     **/
49
 
    protected $_connection = null;
 
62
     */
 
63
    protected $_connection = NULL;
 
64
        
50
65
    /**
51
66
     * Tabla origen de datos
52
67
     *
53
68
     * @var string
54
69
     */
55
 
    protected $_table = null;
 
70
    protected $_table = NULL;
 
71
        
56
72
    /**
57
73
     * Esquema de datos
58
74
     *
59
75
     * @var string
60
76
     */
61
 
    protected $_schema = null;
 
77
    protected $_schema = NULL;
 
78
        
62
79
    /**
63
80
     * Objeto DbQuery para implementar chain
64
81
     * 
65
82
     * @var Obj
66
83
     */
67
84
    protected $_dbQuery = NULL;
68
 
    private $_pointer = 0;
 
85
    
 
86
        /**
 
87
         * Posicion en el iterador
 
88
         *
 
89
         * @var int
 
90
         */
 
91
        private $_pointer = 0;
 
92
        
69
93
    /**
70
94
     * ResulSet PDOStatement
71
95
     * 
72
 
     * @var Obj
 
96
     * @var PDOStatement
73
97
     */
74
 
    private $_resultSet = NULL;
 
98
    protected $_resultSet = NULL;
 
99
        
 
100
        /**
 
101
         * Modo de obtener datos
 
102
         * 
 
103
         * @var integer
 
104
         */
 
105
        protected $_fetchMode = self::FETCH_MODEL;
 
106
        
75
107
    /**
76
108
     * Constructor de la class
 
109
         * 
77
110
     */
78
 
    public function __constructor ($data = null)
 
111
    public function __construct ($data = NULL)
79
112
    {
80
113
        if (is_array($data)) {
81
 
            foreach ($data as $k => $v) {
82
 
                $this->$k = $v;
83
 
            }
84
 
        }
85
 
    }
86
 
    /**
87
 
     * Efectua una busqueda
88
 
     *
89
 
     * @param string|array parametros de busqueda
90
 
     * @return ResultSet
91
 
     **/
92
 
    public function find ()
93
 
    {
94
 
        if(!$this->_dbQuery){
95
 
            // nuevo contenedor de consulta
96
 
            $this->_dbQuery = new DbQuery();
97
 
            $this->_dbQuery->select();
98
 
        }
99
 
        
100
 
        // asigna la tabla
101
 
        $this->_dbQuery->table($this->_table);
102
 
        // asigna el esquema si existe
103
 
        if ($this->_schema) {
104
 
            $this->_dbQuery->schema($this->_schema);
105
 
        }
106
 
        return $this->findBySql($this->_dbQuery);
107
 
    }
108
 
    public function all ()
109
 
    {}
110
 
    /**
111
 
     * Devuelve la instancia para realizar chain
112
 
     * 
113
 
     * @return DbQuery
114
 
     */
115
 
    public function get ()
116
 
    {
117
 
       $this->_dbQuery = new DbQuery();
118
 
       return $this->_dbQuery->select();
119
 
    }
120
 
    /**
121
 
     * Efectua una busqueda de una consulta sql
122
 
     *
123
 
     * @param string | DbQuery $sql
124
 
     * @return ResultSet
125
 
     **/
126
 
    public function findBySql ($sql)
127
 
    {
128
 
        $bind = $sql->getBind();
129
 
        // carga el adaptador especifico para la conexion
130
 
        $adapter = DbAdapter::factory($this->_connection);
131
 
        // si no es un string, entonces es DbQuery
132
 
        if (! is_string($sql)) {
133
 
            $sql = $adapter->query($sql);
134
 
        }
135
 
        // ejecuta la consulta
136
 
        $this->_resultSet = $adapter->pdo()->prepare($sql);
137
 
        if ($this->_resultSet->execute($bind)) {
138
 
            return $this;
139
 
        }
140
 
        return FALSE;
141
 
    }
142
 
    /**
143
 
     * Ejecuta una setencia SQL aplicando Prepared Statement
144
 
     * 
145
 
     * @param string $sql Setencia SQL
146
 
     * @param array $params parametros que seran enlazados al SQL
147
 
     * @return ResulSet
148
 
     */
149
 
    public function sql ($sql, $params = NULL)
150
 
    {
151
 
        // carga el adaptador especifico para la conexion
152
 
        $adapter = DbAdapter::factory($this->_connection);
153
 
        $this->_resultSet = $adapter->pdo()->prepare($sql);
154
 
        if ($this->_resultSet->execute($params)) {
155
 
            return $this;
156
 
        }
157
 
        return FALSE;
158
 
    }
159
 
    /**
160
 
     * Realiza un insert sobre la tabla
161
 
     * 
162
 
     * @param array $data información a ser guardada
163
 
     * @return Bool 
164
 
     */
165
 
    public function insert ($data = null)
166
 
    {
167
 
        // nuevo contenedor de consulta
168
 
        $dbQuery = new DbQuery();
169
 
        // asigna la tabla
170
 
        $dbQuery->table($this->_table);
171
 
        // asigna el esquema si existe
172
 
        if ($this->_schema) {
173
 
            $dbQuery->schema($this->_schema);
174
 
        }
175
 
        $dbQuery->insert($data);
176
 
        $adapter = DbAdapter::factory($this->_connection);
177
 
        try {
178
 
            $prepare = $adapter->pdo()->prepare($adapter->query($dbQuery));
179
 
            return $prepare->execute($data);
180
 
        } catch (PDOException $e) {    //echo $prepare->errorCode();die;
181
 
        }
182
 
        //return FALSE;
183
 
    }
184
 
    /**
185
 
     * Fetch Object
186
 
     * 
187
 
     * @param string Class
188
 
     * @return Array
189
 
     */
190
 
    public function fetchObject ()
191
 
    {
192
 
        $this->_resultSet->setFetchMode(PDO::FETCH_INTO, $this);
193
 
        return $this->_resultSet->fetch();
194
 
    }
 
114
            $this->dump($data);
 
115
        }
 
116
    }
 
117
        
 
118
        /**
 
119
         * Carga el array como atributos del objeto
 
120
         * 
 
121
         * @param array $data
 
122
         */
 
123
        public function dump($data)
 
124
        {
 
125
                foreach ($data as $k => $v) {
 
126
                        $this->$k = $v;
 
127
                }
 
128
        }
 
129
        
 
130
        /**
 
131
         * Callback antes de crear
 
132
         * 
 
133
         * @return boolean
 
134
         */
 
135
        protected function _beforeCreate()
 
136
        {}
 
137
        
 
138
        /**
 
139
         * Callback despues de crear
 
140
         * 
 
141
         * @return boolean
 
142
         */
 
143
        protected function _afterCreate()
 
144
        {}
 
145
        
 
146
        /**
 
147
         * Callback antes de actualizar
 
148
         * 
 
149
         * @return boolean
 
150
         */
 
151
        protected function _beforeUpdate()
 
152
        {}
 
153
        
 
154
        /**
 
155
         * Callback despues de actualizar
 
156
         * 
 
157
         * @return boolean
 
158
         */
 
159
        protected function _afterUpdate()
 
160
        {}
 
161
        
 
162
        /**
 
163
         * Modo de obtener datos 
 
164
         * 
 
165
         * @param integer $mode
 
166
         * @return ActiveRecord
 
167
         */
 
168
        public function setFetchMode($mode) 
 
169
        {
 
170
                $this->_fetchMode = $mode;
 
171
                return $this;
 
172
        }
 
173
        
195
174
    /**
196
175
     * reset result set pointer 
197
176
     * (implementation required by 'rewind()' method in Iterator interface)
200
179
    {
201
180
        $this->_pointer = 0;
202
181
    }
 
182
        
203
183
    /**
204
184
     * get current row set in result set 
205
185
     * (implementation required by 'current()' method in Iterator interface)
207
187
    public function current ()
208
188
    {
209
189
        if (! $this->valid()) {
210
 
            throw new KumbiaException('Unable to retrieve current row.');
 
190
            throw new KumbiaException('No se pude obtener la fila actual');
211
191
        }
212
 
        return $this->fetchObject();
 
192
        return $this->_resultSet->fetch();
213
193
    }
 
194
        
214
195
    /**
215
196
     * Obtiene la posición actual del Puntero 
216
197
     * 
219
200
    {
220
201
        return $this->_pointer;
221
202
    }
 
203
        
222
204
    /**
223
205
     * Mueve el puntero a la siguiente posición 
224
206
     * 
227
209
    {
228
210
        ++ $this->_pointer;
229
211
    }
 
212
        
230
213
    /**
231
214
     * Determina si el puntero del ResultSet es valido 
232
215
     * 
235
218
    {
236
219
        return $this->_pointer < $this->_resultSet->rowCount();
237
220
    }
238
 
    
 
221
        
 
222
        /**
 
223
         * Indica el modo de obtener datos al ResultSet actual
 
224
         * 
 
225
         */
 
226
        protected function _fetchMode($fetchMode = NULL)
 
227
        {
 
228
                // Si no se especifica toma el por defecto
 
229
                if(!$fetchMode) {
 
230
                        $fetchMode = $this->_fetchMode;
 
231
                }
 
232
                
 
233
                switch ($fetchMode) {
 
234
                        // Obtener instancias del mismo modelo
 
235
                        case self::FETCH_MODEL:
 
236
                                // Instancias de un nuevo modelo, por lo tanto libre de los atributos de la instancia actual
 
237
                                $this->_resultSet->setFetchMode(PDO::FETCH_INTO, new self());
 
238
                                break;
 
239
                                
 
240
                        // Obtener instancias de objetos simples
 
241
                        case self::FETCH_OBJ:
 
242
                                $this->_resultSet->setFetchMode(PDO::FETCH_OBJ);
 
243
                                break;
 
244
                                
 
245
                        // Obtener arrays
 
246
                        case self::FETCH_ARRAY:
 
247
                                $this->_resultSet->setFetchMode(PDO::FETCH_ASSOC);
 
248
                                break;
 
249
                }
 
250
        }
 
251
        
 
252
        /**
 
253
         * Asigna la tabla fuente de datos
 
254
         * 
 
255
         * @param string $table
 
256
         * @return ActiveRecord
 
257
         */
 
258
        public function setTable($table)
 
259
        {
 
260
                $this->_table = $table;
 
261
                return $this;
 
262
        }
 
263
        
 
264
        /**
 
265
         * Obtiene la tabla fuente de datos
 
266
         * 
 
267
         * @return string
 
268
         */
 
269
        public function getTable()
 
270
        {
 
271
        // Asigna la tabla
 
272
                if(!$this->_table) {
 
273
                        $this->_table = Util::smallcase(get_class($this));
 
274
                }
 
275
                
 
276
                // Tabla
 
277
                return $this->_table;   
 
278
        }
 
279
        
 
280
        /**
 
281
         * Asigna el schema
 
282
         * 
 
283
         * @param string $schema
 
284
         * @return ActiveRecord
 
285
         */
 
286
        public function setSchema($schema)
 
287
        {
 
288
                $this->_schema = $schema;
 
289
                return $this;
 
290
        }
 
291
        
 
292
        /**
 
293
         * Obtiene el schema
 
294
         * 
 
295
         * @return string
 
296
         */
 
297
        public function getSchema()
 
298
        {
 
299
                return $this->_schema;  
 
300
        }
 
301
        
 
302
        /**
 
303
         * Asigna la conexion
 
304
         * 
 
305
         * @param string $conn
 
306
         * @return ActiveRecord
 
307
         */
 
308
        public function setConnection($conn)
 
309
        {
 
310
                $this->_connection = $conn;
 
311
                return $this;
 
312
        }
 
313
        
 
314
        /**
 
315
         * Obtiene la conexion
 
316
         * 
 
317
         * @return string
 
318
         */
 
319
        public function getConnection()
 
320
        {
 
321
                return $this->_connection;      
 
322
        }
 
323
        
 
324
    /**
 
325
     * Ejecuta una setencia SQL aplicando Prepared Statement
 
326
     * 
 
327
     * @param string $sql Setencia SQL
 
328
     * @param array $params parametros que seran enlazados al SQL
 
329
         * @param string $fetchMode
 
330
     * @return ActiveRecord
 
331
     */
 
332
    public function sql ($sql, $params = NULL, $fetchMode = NULL)
 
333
    {
 
334
                try {                   
 
335
                        // Obtiene una instancia del adaptador y prepara la consulta
 
336
            $this->_resultSet = DbAdapter::factory($this->_connection)->prepare($sql);
 
337
                        
 
338
                        // Indica el modo de obtener los datos en el ResultSet
 
339
                        $this->_fetchMode($fetchMode);
 
340
                        
 
341
                        // Ejecuta la consulta
 
342
            $this->_resultSet->execute($params);
 
343
            return $this;
 
344
        } catch (PDOException $e) {
 
345
            // Aqui debemos ir a cada adapter y verificar el código de error SQLSTATE
 
346
            echo $this->_resultSet->errorCode();
 
347
        }
 
348
                
 
349
        return FALSE;
 
350
    }
 
351
                
 
352
    /**
 
353
     * Ejecuta una consulta de dbQuery
 
354
     * 
 
355
     * @param DbQuery $dbQuery Objeto de consulta
 
356
         * @param string $fetchMode
 
357
     * @return ActiveRecord
 
358
     */
 
359
        public function query($dbQuery, $fetchMode = NULL) 
 
360
        {        
 
361
        $dbQuery->table($this->getTable());
 
362
                
 
363
        // Asigna el esquema si existe
 
364
        if ($this->_schema) {
 
365
            $dbQuery->schema($this->_schema);
 
366
        }
 
367
                   
 
368
                try {                   
 
369
                        // Obtiene una instancia del adaptador y prepara la consulta
 
370
            $this->_resultSet = DbAdapter::factory($this->_connection)->prepareDbQuery($dbQuery);
 
371
                        
 
372
                        // Indica el modo de obtener los datos en el ResultSet
 
373
                        $this->_fetchMode($fetchMode);
 
374
                        
 
375
                        // Ejecuta la consulta
 
376
            $this->_resultSet->execute($dbQuery->getBind());
 
377
            return $this;
 
378
        } catch (PDOException $e) {
 
379
            // Aqui debemos ir a cada adapter y verificar el código de error SQLSTATE
 
380
            echo $this->_resultSet->errorCode();
 
381
        }
 
382
        }
 
383
        
 
384
    /**
 
385
     * Devuelve la instancia para realizar chain
 
386
     * 
 
387
     * @return DbQuery
 
388
     */
 
389
    public function get ()
 
390
    {
 
391
                // Crea la instancia de DbQuery
 
392
        $this->_dbQuery = new DbQuery();
 
393
                                
 
394
        return $this->_dbQuery;
 
395
    }
 
396
        
 
397
    /**
 
398
     * Efectua una busqueda
 
399
     *
 
400
         * @param string $fetchMode
 
401
     * @return ActiveRecord
 
402
     */
 
403
    public function find ($fetchMode = NULL)
 
404
    {
 
405
        if (! $this->_dbQuery) {
 
406
            $this->get();
 
407
        }
 
408
        return $this->query($this->_dbQuery->select(), $fetchMode);
 
409
    }
 
410
        
 
411
        /**
 
412
         * Obtiene un array con los items resultantes de la busqueda
 
413
         * 
 
414
         * @param string $fetchMode
 
415
         * @return array
 
416
         */
 
417
    public function all ($fetchMode = NULL)
 
418
    {
 
419
                return $this->find($fetchMode)->_resultSet->fetchAll();
 
420
        }
 
421
        
 
422
        /**
 
423
         * Obtiene el primer elemento de la busqueda
 
424
         * 
 
425
         * @param string $fetchMode
 
426
         * @return ActiveRecord
 
427
         */
 
428
    public function first ($fetchMode = NULL)
 
429
    {
 
430
        if (! $this->_dbQuery) {
 
431
            $this->get();
 
432
        }
 
433
                
 
434
                // Realiza la busqueda y retorna el objeto ActiveRecord
 
435
                return $this->query($this->_dbQuery->select()->limit(1)->offset(0), $fetchMode)->_resultSet->fetch();
 
436
        }
 
437
                
 
438
        /**
 
439
         * Busca por medio de una columna especifica
 
440
         * 
 
441
         * @param string $column columna de busqueda
 
442
         * @param string $value valor para la busqueda
 
443
         * @param string $fetchMode
 
444
         * @return ActiveRecord
 
445
         */
 
446
        public function findBy($column, $value, $fetchMode = NULL)
 
447
        {
 
448
                $this->get()->where("$column = :value")->bindValue('value', $value);
 
449
                return $this->first($fetchMode);
 
450
        }
 
451
                
 
452
        /**
 
453
         * Busca por medio de una columna especifica y obtiene todas la coincidencias
 
454
         * 
 
455
         * @param string $column columna de busqueda
 
456
         * @param string $value valor para la busqueda
 
457
         * @param string $fetchMode
 
458
         * @return ActiveRecord
 
459
         */
 
460
        public function findAllBy($column, $value, $fetchMode = NULL)
 
461
        {
 
462
                $this->get()->where("$column = :value")->bindValue('value', $value);
 
463
                return $this->find($fetchMode);
 
464
        }
 
465
        
 
466
        /**
 
467
         * Obtiene la clave primaria
 
468
         * 
 
469
         * @return string
 
470
         */
 
471
        public function getPK()
 
472
        {
 
473
                return DbAdapter::factory($this->_connection)->describe($this->getTable(), $this->_schema)->getPK();
 
474
        }
 
475
        
 
476
        /**
 
477
         * Buscar por medio de la clave primaria
 
478
         * 
 
479
         * @param string $value
 
480
         * @param string $fetchMode
 
481
         * @return ActiveRecord
 
482
         */
 
483
        public function findByPK($value, $fetchMode = NULL)
 
484
        {
 
485
                return $this->findBy($this->getPK(), $value, $fetchMode);
 
486
        }
 
487
        
 
488
        /**
 
489
         * Obtiene un array de los atributos que corresponden a columnas
 
490
         * en la tabla
 
491
         * 
 
492
         * @return array
 
493
         */
 
494
        private function _getTableValues()
 
495
        {
 
496
                $data = array();
 
497
                
 
498
                // Itera en cada atributo
 
499
                foreach(DbAdapter::factory($this->_connection)
 
500
                                        ->describe($this->getTable(), $this->_schema)
 
501
                                        ->getAttributesList() as $attr) {
 
502
                                                
 
503
                        if(property_exists($this, $attr)) {
 
504
                                if($this->$attr === '') {
 
505
                                        $data[$attr] = NULL;
 
506
                                } else {
 
507
                                        $data[$attr] = $this->$attr;
 
508
                                }
 
509
                        } else {
 
510
                                $data[$attr] = NULL;
 
511
                        }
 
512
                }
 
513
                
 
514
                return $data;
 
515
        }
 
516
        
 
517
    /**
 
518
     * Realiza un insert sobre la tabla
 
519
     * 
 
520
     * @param array $data información a ser guardada
 
521
     * @return ActiveRecord 
 
522
     */
 
523
    public function create ($data = NULL)
 
524
    {           
 
525
                // Si es un array, se cargan los atributos en el objeto
 
526
        if (is_array($data)) {
 
527
            $this->dump($data);
 
528
        }
 
529
                                
 
530
                // @see ActiveRecordValidator
 
531
                require_once CORE_PATH . 'libs/ActiveRecord/active_record2/active_record_validator.php';
 
532
                
 
533
                // Ejecuta la validacion
 
534
                if(ActiveRecordValidator::validateOnCreate($this) === FALSE) {
 
535
                        return FALSE;
 
536
                }
 
537
                
 
538
                // Callback antes de crear
 
539
                if($this->_beforeCreate() === FALSE) {
 
540
                        return FALSE;
 
541
                }
 
542
                
 
543
                // Nuevo contenedor de consulta
 
544
        $dbQuery = new DbQuery();
 
545
                
 
546
                // Ejecuta la consulta
 
547
                if($this->query($dbQuery->insert($this->_getTableValues()))) {
 
548
                        // Callback despues de crear
 
549
                        $this->_afterCreate();
 
550
                        return $this;
 
551
                }
 
552
                
 
553
                return FALSE;
 
554
    }
 
555
        
 
556
        /**
 
557
     * Realiza un update sobre la tabla
 
558
     * 
 
559
     * @param array $data información a ser guardada
 
560
     * @return Bool
 
561
     */
 
562
    public function updateAll ($data)
 
563
    {
 
564
        if (! $this->_dbQuery) {
 
565
            $this->get();
 
566
        }
 
567
                
 
568
                // Ejecuta la consulta
 
569
                return $this->query($this->_dbQuery->update($data));
 
570
    }
 
571
        
 
572
        /**
 
573
     * Realiza un delete sobre la tabla
 
574
     * 
 
575
     * @return Bool
 
576
     */
 
577
    public function deleteAll ()
 
578
    {
 
579
        if (! $this->_dbQuery) {
 
580
            $this->get();
 
581
        }
 
582
                
 
583
                // Ejecuta la consulta
 
584
                return $this->query($this->_dbQuery->delete());
 
585
    }
 
586
        
 
587
        /**
 
588
         * Validadores
 
589
         * 
 
590
         * @return array
 
591
         */
 
592
        public function validators()
 
593
        {}
 
594
        
 
595
        /**
 
596
         * Cuenta las apariciones de filas
 
597
         * 
 
598
         * @param string $column
 
599
         * @return integer
 
600
         */ 
 
601
        public function count($column = '*')
 
602
        {
 
603
        if (! $this->_dbQuery) {
 
604
            $this->get();
 
605
        }
 
606
                
 
607
                $this->_dbQuery->columns("COUNT($column) AS n");
 
608
                return $this->first(self::FETCH_OBJ)->n;
 
609
        }
 
610
        
 
611
        /**
 
612
         * Verifica si existe al menos una fila con las condiciones indicadas
 
613
         * 
 
614
         * @return boolean
 
615
         */ 
 
616
        public function existsOne()
 
617
        {
 
618
        return $this->count() > 0;
 
619
        }
 
620
        
 
621
        /**
 
622
         * Establece condicion de busqueda con clave primaria
 
623
         * 
 
624
         * @param DbQuery $dbQuery
 
625
         */
 
626
        protected function _wherePK($dbQuery)
 
627
        {
 
628
                // Obtiene la clave primaria
 
629
                $pk = $this->getPK();
 
630
                
 
631
                // Si es clave primaria compuesta
 
632
                if(is_array($pk)) {
 
633
                        foreach($pk as $k) {
 
634
                                if(!isset($this->$k)) {
 
635
                                        throw new KumbiaException("Debe definir valor para la columna $k de la clave primaria");
 
636
                                }
 
637
                                
 
638
                                $dbQuery->where("$k = :pk_$k")->bindValue("pk_$k", $this->$k);
 
639
                        }
 
640
                } else {
 
641
                        if(!isset($this->$pk)) {
 
642
                                throw new KumbiaException("Debe definir valor para la clave primaria");
 
643
                        }
 
644
                        
 
645
                        $dbQuery->where("$pk = :pk_$pk")->bindValue("pk_$pk", $this->$pk);
 
646
                }
 
647
        }
 
648
        
 
649
        /**
 
650
         * Verifica si esta persistente en la BD el objeto actual en la bd
 
651
         * 
 
652
         * @return boolean
 
653
         */
 
654
        public function exists()
 
655
        {
 
656
                // Objeto de consulta
 
657
                $dbQuery = $this->get();
 
658
                
 
659
                // Establece condicion de busqueda con clave primaria
 
660
                $this->_wherePK($dbQuery);
 
661
                
 
662
                return $this->existsOne();
 
663
        }
 
664
        
 
665
        /**
 
666
     * Realiza un update del registro sobre la tabla
 
667
     * 
 
668
     * @param array $data información a ser guardada
 
669
     * @return Bool 
 
670
     */
 
671
        public function update($data = NULL)
 
672
        {                               
 
673
                // Si es un array, se cargan los atributos en el objeto
 
674
        if (is_array($data)) {
 
675
            $this->dump($data);
 
676
        }
 
677
                                
 
678
                // @see ActiveRecordValidator
 
679
                require_once CORE_PATH . 'libs/ActiveRecord/active_record2/active_record_validator.php';
 
680
                
 
681
                // Ejecuta la validacion
 
682
                if(ActiveRecordValidator::validateOnUpdate($this) === FALSE) {
 
683
                        return FALSE;
 
684
                }
 
685
                
 
686
                // Callback antes de actualizar
 
687
                if($this->_beforeUpdate() === FALSE) {
 
688
                        return FALSE;
 
689
                }
 
690
                
 
691
                // Si no existe el registro
 
692
                if(!$this->exists()) {
 
693
                        return FALSE;
 
694
                }
 
695
 
 
696
                // Objeto de consulta
 
697
                $dbQuery = new DbQuery();
 
698
                // Establece condicion de busqueda con clave primaria
 
699
                $this->_wherePK($dbQuery);
 
700
                
 
701
                // Ejecuta la consulta con el query utilizado para el exists
 
702
                if($this->query($dbQuery->update($this->_getTableValues()))) {
 
703
                        // Callback despues de actualizar
 
704
                        $this->_afterUpdate();
 
705
                        return $this;
 
706
                }
 
707
                
 
708
                return FALSE;
 
709
        }
239
710
}