Design Patterns: How to create database object/connection only when needed?

前端 未结 10 1001
野的像风
野的像风 2020-11-29 21:04

I\'ve a simple application, say it has some classes and an \"extra\" one that handles database requests. Currently i\'m creating the database object everytime the app is use

10条回答
  •  无人及你
    2020-11-29 21:45

    I come from the world of Java. Java is resident in memory accross stateless HTML requests. PHP is not. That is a whole different story - and what I like about PHP.

    I simply use: $conn = @pg_connect(DBConnection);

    the DBConnection is a definition containing the information about the host etc.. The @ assures that the current connection is used or a new one is created. How can I do it more easily?

    The data how to connect to the database is stable. The connection itself might be recreated during a request. Why should I program better then the people of PHP and recreate the @? They did that for the PHP community, let's use it.

    By the way, never put heavy objects in a constructor and never let the constructor do some heavy job nor let it happen that an exception can be thrown during construction of an object. You might have an unfinished object resident in your memory. An init-method is to be preferred. I agree on that with Henrique Barcelos.

提交回复
热议问题