~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:
144
144
        {}
145
145
        
146
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
        /**
147
163
         * Modo de obtener datos 
148
164
         * 
149
165
         * @param integer $mode
315
331
     */
316
332
    public function sql ($sql, $params = NULL, $fetchMode = NULL)
317
333
    {
318
 
                // Obtiene una instancia del adaptador
319
 
                $adapter = DbAdapter::factory($this->_connection);
320
 
                
321
334
                try {                   
322
 
                        // Prepara la consulta
323
 
            $this->_resultSet = $adapter->prepare($sql);
 
335
                        // Obtiene una instancia del adaptador y prepara la consulta
 
336
            $this->_resultSet = DbAdapter::factory($this->_connection)->prepare($sql);
324
337
                        
325
338
                        // Indica el modo de obtener los datos en el ResultSet
326
339
                        $this->_fetchMode($fetchMode);
351
364
        if ($this->_schema) {
352
365
            $dbQuery->schema($this->_schema);
353
366
        }
354
 
                     
355
 
                // Obtiene una instancia del adaptador
356
 
                $adapter = DbAdapter::factory($this->_connection);
357
 
                            
 
367
                   
358
368
                try {                   
359
 
                        // Prepara la consulta
360
 
            $this->_resultSet = $adapter->prepareDbQuery($dbQuery);
 
369
                        // Obtiene una instancia del adaptador y prepara la consulta
 
370
            $this->_resultSet = DbAdapter::factory($this->_connection)->prepareDbQuery($dbQuery);
361
371
                        
362
372
                        // Indica el modo de obtener los datos en el ResultSet
363
373
                        $this->_fetchMode($fetchMode);
435
445
         */
436
446
        public function findBy($column, $value, $fetchMode = NULL)
437
447
        {
438
 
                $this->get()->where("$column = :value")->bind(array('value' => $value));
 
448
                $this->get()->where("$column = :value")->bindValue('value', $value);
439
449
                return $this->first($fetchMode);
440
450
        }
441
451
                
449
459
         */
450
460
        public function findAllBy($column, $value, $fetchMode = NULL)
451
461
        {
452
 
                $this->get()->where("$column = :value")->bind(array('value' => $value));
 
462
                $this->get()->where("$column = :value")->bindValue('value', $value);
453
463
                return $this->find($fetchMode);
454
464
        }
455
465
        
456
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
        /**
457
477
         * Buscar por medio de la clave primaria
458
478
         * 
459
479
         * @param string $value
462
482
         */
463
483
        public function findByPK($value, $fetchMode = NULL)
464
484
        {
465
 
                // Obtiene la metadata
466
 
                $metadata = DbAdapter::factory($this->_connection)->describe($this->getTable(), $this->_schema);
467
 
                
468
 
                return $this->findBy($metadata->getPK(), $value, $fetchMode);
 
485
                return $this->findBy($this->getPK(), $value, $fetchMode);
469
486
        }
470
487
        
471
488
        /**
476
493
         */
477
494
        private function _getTableValues()
478
495
        {
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
496
                $data = array();
 
497
                
485
498
                // Itera en cada atributo
486
 
                foreach($metadata->getAttributesList() as $attr) {
 
499
                foreach(DbAdapter::factory($this->_connection)
 
500
                                        ->describe($this->getTable(), $this->_schema)
 
501
                                        ->getAttributesList() as $attr) {
 
502
                                                
487
503
                        if(property_exists($this, $attr)) {
488
504
                                if($this->$attr === '') {
489
505
                                        $data[$attr] = NULL;
502
518
     * Realiza un insert sobre la tabla
503
519
     * 
504
520
     * @param array $data información a ser guardada
505
 
     * @return Bool 
 
521
     * @return ActiveRecord 
506
522
     */
507
523
    public function create ($data = NULL)
508
524
    {           
510
526
        if (is_array($data)) {
511
527
            $this->dump($data);
512
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
                }
513
537
                
514
538
                // Callback antes de crear
515
539
                if($this->_beforeCreate() === FALSE) {
516
540
                        return FALSE;
517
541
                }
518
542
                
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
543
                // Nuevo contenedor de consulta
528
544
        $dbQuery = new DbQuery();
529
545
                
531
547
                if($this->query($dbQuery->insert($this->_getTableValues()))) {
532
548
                        // Callback despues de crear
533
549
                        $this->_afterCreate();
534
 
                        return TRUE;
 
550
                        return $this;
535
551
                }
536
552
                
537
553
                return FALSE;
603
619
        }
604
620
        
605
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
        /**
606
650
         * Verifica si esta persistente en la BD el objeto actual en la bd
607
651
         * 
608
652
         * @return boolean
609
653
         */
610
654
        public function exists()
611
655
        {
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));
 
656
                // Objeto de consulta
 
657
                $dbQuery = $this->get();
 
658
                
 
659
                // Establece condicion de busqueda con clave primaria
 
660
                $this->_wherePK($dbQuery);
623
661
                
624
662
                return $this->existsOne();
625
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
        }
626
710
}