~desarrollokumbia/kumbia/ActiveRecord

« back to all changes in this revision

Viewing changes to active_record2/active_record2.php

  • Committer: Emilio Silveira
  • Date: 2010-07-12 04:47:04 UTC
  • Revision ID: emilio.rst@gmail.com-20100712044704-2pwwlq8ypfvwwusc
Comenzando con las validaciones al crear y adicionados otros metodos 
utiles

Show diffs side-by-side

added added

removed removed

Lines of Context:
41
41
         * Obtener datos cargados en objeto del Modelo
42
42
         * 
43
43
         */
44
 
        const FETCH_MODEL = 1;
 
44
        const FETCH_MODEL = 'model';
45
45
        
46
46
        /**
47
47
         * Obtener datos cargados en objeto
48
48
         * 
49
49
         */
50
 
        const FETCH_OBJ = 2;
 
50
        const FETCH_OBJ = 'obj';
51
51
        
52
52
        /**
53
53
         * Obtener datos cargados en array
54
54
         * 
55
55
         */
56
 
        const FETCH_ARRAY = 3;
 
56
        const FETCH_ARRAY = 'array';
57
57
                
58
58
    /**
59
59
     * Conexion a base datos que se utilizara
60
60
     *
61
61
     * @var strings
62
62
     */
63
 
    protected $_connection = null;
 
63
    protected $_connection = NULL;
64
64
        
65
65
    /**
66
66
     * Tabla origen de datos
67
67
     *
68
68
     * @var string
69
69
     */
70
 
    protected $_table = null;
 
70
    protected $_table = NULL;
71
71
        
72
72
    /**
73
73
     * Esquema de datos
74
74
     *
75
75
     * @var string
76
76
     */
77
 
    protected $_schema = null;
 
77
    protected $_schema = NULL;
78
78
        
79
79
    /**
80
80
     * Objeto DbQuery para implementar chain
95
95
     * 
96
96
     * @var PDOStatement
97
97
     */
98
 
    private $_resultSet = NULL;
 
98
    protected $_resultSet = NULL;
99
99
        
100
100
        /**
101
101
         * Modo de obtener datos
108
108
     * Constructor de la class
109
109
         * 
110
110
     */
111
 
    public function __construct ($data = null)
 
111
    public function __construct ($data = NULL)
112
112
    {
113
113
        if (is_array($data)) {
114
 
            $this->_dump($data);
 
114
            $this->dump($data);
115
115
        }
116
116
    }
117
117
        
120
120
         * 
121
121
         * @param array $data
122
122
         */
123
 
        protected function _dump($data)
 
123
        public function dump($data)
124
124
        {
125
125
                foreach ($data as $k => $v) {
126
126
                        $this->$k = $v;
128
128
        }
129
129
        
130
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
        /**
131
147
         * Modo de obtener datos 
132
148
         * 
133
149
         * @param integer $mode
191
207
         * Indica el modo de obtener datos al ResultSet actual
192
208
         * 
193
209
         */
194
 
        protected function _fetchMode()
 
210
        protected function _fetchMode($fetchMode = NULL)
195
211
        {
196
 
                switch ($this->_fetchMode) {
 
212
                // Si no se especifica toma el por defecto
 
213
                if(!$fetchMode) {
 
214
                        $fetchMode = $this->_fetchMode;
 
215
                }
 
216
                
 
217
                switch ($fetchMode) {
197
218
                        // Obtener instancias del mismo modelo
198
219
                        case self::FETCH_MODEL:
 
220
                                // Instancias de un nuevo modelo, por lo tanto libre de los atributos de la instancia actual
199
221
                                $this->_resultSet->setFetchMode(PDO::FETCH_INTO, new self());
200
222
                                break;
201
223
                                
261
283
                return $this->_schema;  
262
284
        }
263
285
        
 
286
        /**
 
287
         * Asigna la conexion
 
288
         * 
 
289
         * @param string $conn
 
290
         * @return ActiveRecord
 
291
         */
 
292
        public function setConnection($conn)
 
293
        {
 
294
                $this->_connection = $conn;
 
295
                return $this;
 
296
        }
 
297
        
 
298
        /**
 
299
         * Obtiene la conexion
 
300
         * 
 
301
         * @return string
 
302
         */
 
303
        public function getConnection()
 
304
        {
 
305
                return $this->_connection;      
 
306
        }
 
307
        
264
308
    /**
265
309
     * Ejecuta una setencia SQL aplicando Prepared Statement
266
310
     * 
267
311
     * @param string $sql Setencia SQL
268
312
     * @param array $params parametros que seran enlazados al SQL
 
313
         * @param string $fetchMode
269
314
     * @return ActiveRecord
270
315
     */
271
 
    public function sql ($sql, $params = NULL)
 
316
    public function sql ($sql, $params = NULL, $fetchMode = NULL)
272
317
    {
273
318
                // Obtiene una instancia del adaptador
274
319
                $adapter = DbAdapter::factory($this->_connection);
278
323
            $this->_resultSet = $adapter->prepare($sql);
279
324
                        
280
325
                        // Indica el modo de obtener los datos en el ResultSet
281
 
                        $this->_fetchMode();
 
326
                        $this->_fetchMode($fetchMode);
282
327
                        
283
328
                        // Ejecuta la consulta
284
329
            $this->_resultSet->execute($params);
295
340
     * Ejecuta una consulta de dbQuery
296
341
     * 
297
342
     * @param DbQuery $dbQuery Objeto de consulta
 
343
         * @param string $fetchMode
298
344
     * @return ActiveRecord
299
345
     */
300
 
        public function query($dbQuery) 
 
346
        public function query($dbQuery, $fetchMode = NULL) 
301
347
        {        
302
348
        $dbQuery->table($this->getTable());
303
349
                
314
360
            $this->_resultSet = $adapter->prepareDbQuery($dbQuery);
315
361
                        
316
362
                        // Indica el modo de obtener los datos en el ResultSet
317
 
                        $this->_fetchMode();
 
363
                        $this->_fetchMode($fetchMode);
318
364
                        
319
365
                        // Ejecuta la consulta
320
366
            $this->_resultSet->execute($dbQuery->getBind());
341
387
    /**
342
388
     * Efectua una busqueda
343
389
     *
 
390
         * @param string $fetchMode
344
391
     * @return ActiveRecord
345
392
     */
346
 
    public function find ()
 
393
    public function find ($fetchMode = NULL)
347
394
    {
348
395
        if (! $this->_dbQuery) {
349
396
            $this->get();
350
397
        }
351
 
        return $this->query($this->_dbQuery->select());
 
398
        return $this->query($this->_dbQuery->select(), $fetchMode);
352
399
    }
353
400
        
354
401
        /**
355
402
         * Obtiene un array con los items resultantes de la busqueda
356
403
         * 
 
404
         * @param string $fetchMode
357
405
         * @return array
358
406
         */
359
 
    public function all ()
 
407
    public function all ($fetchMode = NULL)
360
408
    {
361
 
                return $this->find()->_resultSet->fetchAll();
 
409
                return $this->find($fetchMode)->_resultSet->fetchAll();
362
410
        }
363
411
        
364
412
        /**
365
413
         * Obtiene el primer elemento de la busqueda
366
414
         * 
 
415
         * @param string $fetchMode
367
416
         * @return ActiveRecord
368
417
         */
369
 
    public function first ()
 
418
    public function first ($fetchMode = NULL)
370
419
    {
371
420
        if (! $this->_dbQuery) {
372
421
            $this->get();
373
422
        }
374
423
                
375
424
                // Realiza la busqueda y retorna el objeto ActiveRecord
376
 
                return $this->query($this->_dbQuery->select()->limit(1)->offset(0))->_resultSet->fetch();
 
425
                return $this->query($this->_dbQuery->select()->limit(1)->offset(0), $fetchMode)->_resultSet->fetch();
377
426
        }
378
427
                
379
428
        /**
381
430
         * 
382
431
         * @param string $column columna de busqueda
383
432
         * @param string $value valor para la busqueda
 
433
         * @param string $fetchMode
384
434
         * @return ActiveRecord
385
435
         */
386
 
        public function findBy($column, $value)
 
436
        public function findBy($column, $value, $fetchMode = NULL)
387
437
        {
388
438
                $this->get()->where("$column = :value")->bind(array('value' => $value));
389
 
                return $this->first();
 
439
                return $this->first($fetchMode);
390
440
        }
391
441
                
392
442
        /**
394
444
         * 
395
445
         * @param string $column columna de busqueda
396
446
         * @param string $value valor para la busqueda
 
447
         * @param string $fetchMode
397
448
         * @return ActiveRecord
398
449
         */
399
 
        public function findAllBy($column, $value)
 
450
        public function findAllBy($column, $value, $fetchMode = NULL)
400
451
        {
401
452
                $this->get()->where("$column = :value")->bind(array('value' => $value));
402
 
                return $this->find();
 
453
                return $this->find($fetchMode);
403
454
        }
404
455
        
405
456
        /**
406
457
         * Buscar por medio de la clave primaria
407
458
         * 
408
459
         * @param string $value
409
 
         */
410
 
        public function findByPK($value)
411
 
        {
412
 
                // Obtiene una instancia del adaptador
413
 
                $adapter = DbAdapter::factory($this->_connection);
414
 
                $metadata = $adapter->describe($this->getTable(), $this->_schema);
415
 
                
416
 
                return $this->findBy($metadata->getPK(), $value);
 
460
         * @param string $fetchMode
 
461
         * @return ActiveRecord
 
462
         */
 
463
        public function findByPK($value, $fetchMode = NULL)
 
464
        {
 
465
                // Obtiene la metadata
 
466
                $metadata = DbAdapter::factory($this->_connection)->describe($this->getTable(), $this->_schema);
 
467
                
 
468
                return $this->findBy($metadata->getPK(), $value, $fetchMode);
 
469
        }
 
470
        
 
471
        /**
 
472
         * Obtiene un array de los atributos que corresponden a columnas
 
473
         * en la tabla
 
474
         * 
 
475
         * @return array
 
476
         */
 
477
        private function _getTableValues()
 
478
        {
 
479
                // Obtiene la metadata
 
480
                $metadata = DbAdapter::factory($this->_connection)->describe($this->getTable(), $this->_schema);
 
481
                
 
482
                // TODO: Falta el caso de la clave primaria autogenerada y completar con NULL cuando la propiedad no existe
 
483
                
 
484
                $data = array();
 
485
                // Itera en cada atributo
 
486
                foreach($metadata->getAttributesList() as $attr) {
 
487
                        if(property_exists($this, $attr)) {
 
488
                                if($this->$attr === '') {
 
489
                                        $data[$attr] = NULL;
 
490
                                } else {
 
491
                                        $data[$attr] = $this->$attr;
 
492
                                }
 
493
                        } else {
 
494
                                $data[$attr] = NULL;
 
495
                        }
 
496
                }
 
497
                
 
498
                return $data;
417
499
        }
418
500
        
419
501
    /**
423
505
     * @return Bool 
424
506
     */
425
507
    public function create ($data = NULL)
426
 
    {
427
 
        // Nuevo contenedor de consulta
 
508
    {           
 
509
                // Si es un array, se cargan los atributos en el objeto
 
510
        if (is_array($data)) {
 
511
            $this->dump($data);
 
512
        }
 
513
                
 
514
                // Callback antes de crear
 
515
                if($this->_beforeCreate() === FALSE) {
 
516
                        return FALSE;
 
517
                }
 
518
                
 
519
                // @see ActiveRecordValidator
 
520
                require_once CORE_PATH . 'libs/ActiveRecord/active_record2/active_record_validator.php';
 
521
                
 
522
                // Ejecuta la validacion
 
523
                if(ActiveRecordValidator::validateOnCreate($this) === FALSE) {
 
524
                        return FALSE;
 
525
                }
 
526
                
 
527
                // Nuevo contenedor de consulta
428
528
        $dbQuery = new DbQuery();
429
529
                
430
530
                // Ejecuta la consulta
431
 
                return $this->query($dbQuery->insert($data));
 
531
                if($this->query($dbQuery->insert($this->_getTableValues()))) {
 
532
                        // Callback despues de crear
 
533
                        $this->_afterCreate();
 
534
                        return TRUE;
 
535
                }
 
536
                
 
537
                return FALSE;
432
538
    }
433
539
        
434
540
        /**
461
567
                // Ejecuta la consulta
462
568
                return $this->query($this->_dbQuery->delete());
463
569
    }
 
570
        
 
571
        /**
 
572
         * Validadores
 
573
         * 
 
574
         * @return array
 
575
         */
 
576
        public function validators()
 
577
        {}
 
578
        
 
579
        /**
 
580
         * Cuenta las apariciones de filas
 
581
         * 
 
582
         * @param string $column
 
583
         * @return integer
 
584
         */ 
 
585
        public function count($column = '*')
 
586
        {
 
587
        if (! $this->_dbQuery) {
 
588
            $this->get();
 
589
        }
 
590
                
 
591
                $this->_dbQuery->columns("COUNT($column) AS n");
 
592
                return $this->first(self::FETCH_OBJ)->n;
 
593
        }
 
594
        
 
595
        /**
 
596
         * Verifica si existe al menos una fila con las condiciones indicadas
 
597
         * 
 
598
         * @return boolean
 
599
         */ 
 
600
        public function existsOne()
 
601
        {
 
602
        return $this->count() > 0;
 
603
        }
 
604
        
 
605
        /**
 
606
         * Verifica si esta persistente en la BD el objeto actual en la bd
 
607
         * 
 
608
         * @return boolean
 
609
         */
 
610
        public function exists()
 
611
        {
 
612
                // Obtiene la clave primaria
 
613
                $metadata = DbAdapter::factory($this->_connection)->describe($this->getTable(), $this->_schema);
 
614
                $pk = $metadata->getPK();
 
615
                
 
616
                // Si no esta definido valor para clave primaria
 
617
                if(!isset($this->$pk) || !$this->$pk) {
 
618
                        return FALSE;
 
619
                }
 
620
                
 
621
                // Establece la condicion de busqueda por clave primaria
 
622
                $this->get()->where("$pk = :$pk")->bind(array($pk => $this->$pk));
 
623
                
 
624
                return $this->existsOne();
 
625
        }
464
626
}