SObject Factory - wimvelzeboer/fflib-apex-extensions GitHub Wiki

SObject Factory

Table of Contents

The fflib_SObjectFactory is a dynamic template for creating records of any SObjectType

Basic methods

Creating Existing Records

In many cases we only need to update fields on records, and do not require the existing data. Therefore, we can create a record in memory with just only its record id. We can pass that record into a domain to set values.

IContacts contacts = Contacts.newInstance(contactIds);
Set<Id> accountIds = contacts.getAccountIds();
IAccounts accounts =
    Accounts.newInstance(
        AccountsFactory.generateById(accountIds)
    );

The static factory class routing to the correct implementation

public with sharing class AccountsFactory
{
    public static List<Account> generateAccountsById(Set<Id> accountIds)
    {
        return factory().generateAccountsById(accountIds);
    }

    private static IAccountsFactory factory()
    {
        return (IAccountsFactory) Application.Factory.newInstance(IAccountsFactory.class);
    }
}

The Factory interface class:

public interface IAccountsFactory extends fflib_ISObjectFactory
{
    List<Account> generateAccountsById(Set<Id> accountIds);
}

The Factory implementation:

public inherited sharing class AccountsFactoryImpl
        extends fflib_SObjectFactory
        implements IAccountsFactory
{
	public List<Account> generateAccountsById(Set<Id> accountIds)
	{
		return (List<Account>) generateSObjectById(accountIds);
	}

	public Schema.SObjectType getSObjectType()
	{
		return Schema.Account.SObjectType;
	}
}

The Application class

public with sharing class Application
{
    ...

    public static final fflib_IServiceFactory Factory =
        new fflib_ClassicServiceFactory(
                new Map<Type, Type>
                {
                        IAccountsFactory.class => AccountsFactoryImpl.class
                }
        );
    ...
}
⚠️ **GitHub.com Fallback** ⚠️