We study theoretically the interaction between two photons in a nonlinear cavity. The photons are absorbed into the cavity by an effective tuning of its input-output coupling via external control of a coupling to a second, strongly output-coupled cavity mode. Such "dynamically coupled" cavities, which can be implemented using bulk chi((2)) and chi((3)) nonlinearities, enable incoming photon wave packets to be absorbed into the cavity with high fidelity when the duration of the control is similar to that of the wave packets. Further, this configuration can be used to avoid limitations in the photon-photon interaction time set by the delay-bandwidth product of passive cavities and enables the elimination of wave-packet distortions caused by dispersive cavity transmission and reflection. We consider three kinds of nonlinearities, two arising from chi((2)) and chi((3)) materials and one due to an interaction with a two-level emitter. To analyze the input and output of few-photon wave packets, we use a Schrodinger-picture formalism in which traveling-wave fields are discretized into infinitesimal time bins. We suggest that dynamically coupled cavities provide a very useful tool for improving the performance of quantum devices relying on cavity-enhanced light-matter interactions such as single-photon sources and atomlike quantum memories with photon interfaces. As an example, we present simulation results showing that high-fidelity two-qubit entangling gates may be constructed using any of the considered nonlinear interactions.