Atoms and molecules in cavities: A method for study of spatial confinement effects