Carriers are the only one who has the authority to unlock an iPhone.
They must request that Apple does this, but the process is largely automated in the countries where unlocking is permitted.
At a basic level, the process involves the carrier telling Apple the specific IMEI of a phone to unlock. Apple maintains a database of all iPhones ever sold and which network they are locked to. When they receive an unlock request from a carrier, the specific IMEI is set to be "unlocked" in the database - a change which usually takes effect when you next sync the phone with iTunes.
It's not possible to unlock an iPhone using "codes".
The whole idea of "locking" a phone is purely beneficial to the carrier. It ensures that their subsidy is recouped and it makes it harder for people to switch to a different carrier. It doesn't really benefit Apple to have a locked iPhone.