Basic Fetching

Examples of simple use-cases for reading data.

Reading Data

There are two ways of selecting data - the simplest is to use the find methods with an array of criteria, as shown below. More complex requirements can be handled using custom queries.

Here are some quick code samples showing how to read data from a standard Objectiphy repository. Note that if you did not specify an entity class name when you defined the dependencies, you will usually need to do so before you call any of these methods: $repository->setClassName($className);. The Objectiphy findBy and findOneBy methods are a little more sophisticated than their Doctrine equivalents (Doctrine uses a separate 'matching' method with expressions, or DQL, for more complex requirements instead).

Example 1: Find by ID, as per doctrine

$policy = $repository->find(19086207);

Example 2: Find by child property (not possible in Doctrine)

$policy2 = $repository->findOneBy(['vehicle.regNo' => 'PJ63LXR']);

Example 3: Find by child ID, as per doctrine

$policy3 = $repository->findOneBy(['customer' => 14247]);

Example 4: Find by child object

//Assuming $customer already holds a customer entity
$policy3 = $repository->findOneBy(['customer' => $customer]);

Example 5: Load with LIKE (or any other) operator

$criteria = [
    'policyNo' => [
        'operator' => 'LIKE',
        'value' => 'UKCAR123%'
    ]
];
$policies = $repository->findBy($criteria);

Example 6: Load flat array of data (not bound to entities)

use Objectiphy\Objectiphy\Config\ConfigOptions;

$repository->setConfigOption(ConfigOptions::BIND_TO_ENTITIES, false);
$policiesArray = $repository->findBy([
    'policyNo' => [
        'operator' => 'LIKE',
        'value' => 'UKCAR123%'
    ]
]);

Example 7: Load a single value from a single property of a single entity

$regNo = $repository->findOneValueBy(
    ['contact.id' => 123], 
    'vehicle.regNo'
);

Example 8: Load an array of single values from a single property of multiple entities

$regNos = $repository->findValuesBy(
    ['contact.lastName' => 'Smith'], 
    'vehicle.regNo'
);

Last updated