Jump to content

Consolidating redundant code... how to make function or class?


cgm225

Recommended Posts

I have two pieces of code that are the same with the exception of one word ("albums" versus "photos" in this example), and I want to know how to be turn the code into a function or class so I only need to include it once?  I am having problems with syntax because those words do not always "stand alone" in the code, but are sometimes part of a camelcase value, etc.

 

Here is the code...

 

Here it is used for "albums"::

        //Adds total number of entries to the registry
        $this->registry->set('totalEntries', $albums->getDataCount());
        
        //Includes/instantiates class to specify number displayed per page
        require_once $this->pageDir . '/NumberDisplayed.php5';
        $numberDisplayed = new NumberDisplayed('albums', 4);
        
        //Adds numberDisplayed per page variable to the registry
        $numberDisplayed = $numberDisplayed->getNumberDisplayed();
        $this->registry->set('albumsDisplayed', $numberDisplayed);

 

Here it is used for "photos"::

        //Adds album directory and total number of photos to the registry
        $this->registry->set('totalEntries', $photos->getDataCount());

        //Includes/instantiates class to specify number displayed per page
        require_once $this->pageDir . '/NumberDisplayed.php5';
        $numberDisplayed = new NumberDisplayed('photos', 4);
        
        //Adds numberDisplayed per page variable to the registry
        $numberDisplayed = $numberDisplayed->getNumberDisplayed();
        $this->registry->set('photosDisplayed', $numberDisplayed);

 

Any ideas on how to consolidate this code?

 

Thanks in advance!

That's a hackish solution, that certainly could and should be done better:

 

function addTotalToRegistry($what) {

        $this->registry->set('totalEntries', $$what->getDataCount());

        //Includes/instantiates class to specify number displayed per page
        require_once $this->pageDir . '/NumberDisplayed.php5';
        $numberDisplayed = new NumberDisplayed($what, 4);
        
        //Adds numberDisplayed per page variable to the registry
        $numberDisplayed = $numberDisplayed->getNumberDisplayed();
        $this->registry->set($what.'Displayed', $numberDisplayed);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.