In the sentence I buy a cake, cake is the direct object of the transitive verb buy. If I write instead I buy him a cake, is cake still the object, or is him now the object of a new verb buy with a different meaning to the verb buy in the first sentence?
The cake is still the object of the sentence.
I buy a cake (for him).
The original sentence hasn't changed, except that now you have a verb, a noun, and a preposition.
I buy him a cake.
It's still the cake that's the object of the verb, but him (and the assumed for) has simply moved between the verb and the noun.
If him were actually the object, then you would be buying him, not buying the cake.
Updated to include additional information from comments.
When for him is put at the end of the sentence, it is a preposition. But what is him itself (especially when placed after the verb on its own)?
It's an indirect object:
Indirect objects are nouns or pronouns that identify to whom or for whom the action of the verb is performed, as well as who is receiving the direct object. Indirect objects are seen infrequently. In order to have an indirect object, there is a direct object. The indirect object typically precedes the direct object and is identified by asking who or what received the direct object. Consider the following examples:
. . .
Example 2: Marc paints the house for his family.
“Marc” is the subject, and “paints” is the verb. Ask the question “paints what?” “The house” is the direct object. To determine the indirect object, ask for whom did the subject do the action? “For his family” is the indirect object.
Sometimes an indirect object comes before the direct object. Consider the following example:
Example 3: Alexa gave me her algebra notes.
“Alexa” is the subject, and “gave” is the verb. Ask the question “gave what?” “Algebra notes” is the direct object. To determine the indirect object, ask for whom did the subject do the action? “Me” is the indirect object, and it came before the direct object in this sentence.