Search code examples
phppropel

Populate key or call method during result set iteration


I'm using Propel to retrieve a list of products, some of the products have an image associated with them which is located within an uploads folder and is based on the image id (for example /uploads/products/product_12.jpg) would be the image the product with an id of 12.

As this image record is not stored in the database as a column, I'm unsure as how can I access the image without having to do checks such as file_exists() within the view.

Is it possible to either have a method smilar to $product->getImage() which either returns the image or returns a blank 'Image does not exist' image, or even better, create a key called image which does the same as above and can be accessed via $product->image.


Solution

  • Of course.

    Inside your model class (not the Peer one, the other one), create this method getImage() wich will basically do :

    public function getImage()
    {
      $filepath = '/uploads/products/product_'.$this->getId().'.jpg';
      if (!file_exists($filepath))
      {
        // image doesn't exist, return false or an empty default image
        return false;
      }
    
      return $filepath;
    }