1
\$\begingroup\$

I have a 'Membership' model that keeps track of a Member's membership. A membership can be updated by an admin (admin_add), or by the user (update). This code is working great, but I'd love some feedback on how it looks, sections that could be improved, etc.

Membership Model: 

class Membership extends AppModel {


        /**
         * Validation rules
         *
         * @var array
         */
        public $validate = array(
                'membership_type_id' => array(
                        'notempty' => array(
                                'rule' => 'notBlank',
                                'message' => 'Membership Type Required',
                                'allowEmpty' => false,
                                'required' => true,
                        ),
                        'validateMembership' => array(
                                'rule' => 'validateMembershipTypeModel',
                                'message' => 'Invalid Membership Type',
                        ),
                ),
                'updated_by_member_id' => array(
                        'validateMember' => array(
                                'rule' => 'validateMemberId',
                                'message' => 'Invalid Updated By Member ID',
                                'allowEmpty' => true,
                        ),
                ),
                'payment_id' => array(
                        'validatePayment' => array(
                                'rule' => 'validatePayment',
                                'message' => 'Invalid Payment ID',
                                'allowEmpty' => true,
                        ),
                ),
                'expires' => array(
                'rule' => array('date', 'ymd'),
                'message' => 'Please enter a valid expiration date',
                'allowEmpty' => false,
                'required' => true
            ), 
            'renewed' => array(
                'rule' => array('date', 'ymd'),
                'message' => 'Please enter a valid renewal date',
                'allowEmpty' => true,
            ), 
        );


        /*
        * Validation function to make sure the membership type id is valid
        *
        * @return bool
        */
        public function validateMembershipTypeModel($check) {

                $mTypeModel = ClassRegistry::init('MembershipType');
                if($mTypeModel->validateMembershipType($this->data['Membership']['membership_type_id'])) {
                        return true;
                }

                return false;
    }

    /*
        * Validation function to make sure the "updated_by_member_id" is valid (a valid member)
        *
        * @return bool
        */
        public function validateMemberId($check) {
                if(! isset($this->data['Membership']['updated_by_member_id'])) {
                        return false;
                }

                $mModel = ClassRegistry::init('Member');
                $mModel->contain();

                if($mModel->findById($this->data['Membership']['updated_by_member_id'])) {

                        return true;
                }

                return false;
    }

     /*
        * Validation function to make sure the payment ID is valid
        *
        * UPDATE
        *
        * @return bool
        */
        public function validatePayment($check) {
                return true;
    }

        /**
         * belongsTo associations
         *
         * @var type array
        */
        public $belongsTo = array(
                'Member',
                'MembershipType'
        );

        /*
        * Validate Membership Data
        *
        * return array membership data
        */
        public function _validateMembershipData($data = array()) {

                // Validate 'corporate' flag
                if(isset($data['corporate']) && $data['corporate'] == 'on') {
                        $data['corporate'] = 1;
                }

                // Validate 'international' flag
                if(isset($data['international']) && $data['international'] == 'on') {
                        $data['international'] = 1;
                }

                return $data;
        }

        /*
        * Create new membership
        * Anytime a membership is updated, this function is called
        *
        *
        * return integer membershipID
        */
        public function createNewMembership($data) {

                if(empty($data)) {
                        return false;
                }

                // Validate data
                $membership_data = $this->_validateMembershipData($data);

                $this->set($membership_data);
                if ($this->validates()) {

                        // Save data           
                        $this->create();
                        if(! $this->save($membership_data)) {
                                throw new NotFoundException('Could not find save membership');
                        }

                        // Assign the membership_id to the member
                        if(! $this->assignMembershipToMember($this->id, $data['member_id'])) {
                                throw new NotFoundException('Could not find save membership_id to member');
                        }

                        // Return Membership ID
                        return $this->id;
                }

                return false;
        }

        /*
        * Assign a membership id to a member
        *
        * param membership_id
        * param member id
        * return bool on success
        */
        public function assignMembershipToMember($membership_id, $member_id) {
                $member = ClassRegistry::init('Member');       
                $member->id = $member_id;

                if($member->saveField('membership_id', $membership_id)) {
                        return true;
                }

                return false;
        }

}


/**
 * Memberships Controller
 *
 * @property Membership $Membership
 * @property PaginatorComponent $Paginator
 * @property SessionComponent $Session
 */
class MembershipsController extends AppController {

        public $uses = array('Member', 'Membership', 'MembershipType');

        /**
         * admin_update method - Update a member's Membership
         *
         * @throws NotFoundException
         * @param integer $id
         * @return void
         */
        public function admin_update($id = null) {

                // Validate the member id
                $this->Member->contain('Membership');
                $member = $this->Member->findById($id);

                if (! $this->Member->exists($id)) {
                        throw new NotFoundException(__('Invalid member'));
                }

                if ($this->request->is(array('post', 'put'))) {

                        // Fill in some of the membership data manually
                        $this->request->data['Membership']['updated_by_member_id'] = $this->Auth->user('id');
                        $this->request->data['Membership']['member_id'] = $id;
                        $this->request->data['Membership']['renewed'] = date('Y-m-d');
                        $this->request->data['Membership']['created_by'] = 'MANUAL';

                        // Create the membership
                        if ($this->Membership->createNewMembership($this->request->data['Membership'])) {
                                $this->Session->setFlash(__('Membership Updated.'), 'success');
                                return $this->redirect(array('admin' => false, 'controller' => 'members', 'action' => 'view', $id));
                        } else {
                                $this->Session->setFlash(__('There was an error updating the membership. Please try again.'), 'error');
                        }
                } else {
                        $this->request->data = $this->Membership->find('first', array('conditions' => array('id' => $member['Member']['membership_id'])));                     
                }

        }

        /**
         * update method - Update a member's Membership
         *
         * @throws NotFoundException
         * @param integer $id
         * @return void
         */
        public function update($membership_type_id = null) {

                // Validate the membership type id
                $this->MembershipType->contain();
                $membership_type = $this->MembershipType->findById($membership_type_id);
                if(! $membership_type) {
                        $this->Session->setFlash("Invalid Membership Type", 'error');
                        return $this->redirect('/');
                }

                // Set the member ID to the person logged in
                $memberId = $this->Auth->user('id');

                // If they are submitting
                if ($this->request->is('post')) {

                        // Assume true for testing
                        $payment = true;
                        $international = true;

                        if($payment === true) {

                                // Build the membership data
                                $membership_data = array(
                                        'member_id' => $memberId,
                                        'membership_type_id' => $membership_type_id,
                                        'renewed' => date('Y-m-d'),
                                        'expires' => date('Y-m-d', strtotime("+1 year")),
                                );

                                // Create a new membership
                                if($this->Membership->createNewMembership($membership_data)) {
                                        $this->Session->setFlash("Success! Your membership has been updated! Please make sure your address is correct below!", 'success');
                                        return $this->redirect(array('controller' => 'members', 'action' => 'view'));
                                }  else {
                                        $this->Session->setFlash(__('There was an error updating the membership. Please try again.'), 'error');
                                }
                        }
                }

                $this->set(compact('membership_type'));
        }
}
\$\endgroup\$
2
\$\begingroup\$

The only thing I would suggest you to do is to remove lines where you initialize models MembershipType and Member since you already have model associations set up correctly. For example, instead of:

$mTypeModel = ClassRegistry::init('MembershipType');
if ($mTypeModel->validateMembershipType($this->data['Membership']['membership_type_id'])) {
    return true;
}

you can do it like this:

if ($this->MembershipType->validateMembershipType($this->data['Membership']['membership_type_id'])) {
   return true;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.