XF 2.1 Syntax for $finder->where with LIKE

abdfahim

Well-known member
Is there any risk with where('tag', 'like', '%'.$search.'%')? I can see XF internally uses something like where('tag', 'like', $finder->escapeLike($search, '?%')), however, I need to pass where clause to repository, so not sure if I can use $finder->escapeLike.

Here is what I am doing now

PHP:
$where = [];

if($params['pname'] != ''){
    array_push($where, ['User.username', 'LIKE', '%'.$params['pname'].'%']);
}

if($params['par1'] != ''){
    array_push($where, ['col1', 'LIKE', '%'.$params['par1'].'%']);
}

if($params['par2'] != ''){
    array_push($where, ['col1', 'LIKE', '%'.$params['par2'].'%']);
}

/** @var \AbdForo\TestPortal\Repository\TestPortal $repo */
$repo = $this->repository('AbdForo\TestPortal:TestPortal');

$finder = $repo->findMDTimelineForPortalView($where);

PHP:
public function findTestPortalView(array $where = [])
{
    $finder = $this->finder('AbdForo\TestPortal:TestPortal');
    $finder ->with('User', true) ->where($where);
    return $finder;
}
 
I would just refactor your code so you can use the finder directly. You could extend the finder with custom methods that do what you want, or simply call findTestPortalView() first and configure it as needed after.
 
Thanks! That make sense though I so wanted to use those fancy repos!

So, I'll change to something like
PHP:
$finder = $this->finder('AbdForo\TestPortal:TestPortal');
$finder->with('User', true);

if($params['pname'] != ''){
    $finder->where(['User.username', 'LIKE', $finder->escapeLike($params['pname'])]);
}

if($params['par1'] != ''){
    $finder->where(['col1', 'LIKE', $finder->escapeLike($params['par1'])]);
}

$results = $finder->fetch();
 
You can still fetch the finder object from the repository and then configure it after. The repository methods are mostly for common finder configurations and to provide extension points for other add-ons. If the configuration you're doing is not unique you can DRY it up by making it a custom finder method.
 
Top Bottom