当前位置: 首页>>代码示例>>PHP>>正文


PHP DB::connect方法代码示例

本文整理汇总了PHP中SilverStripe\ORM\DB::connect方法的典型用法代码示例。如果您正苦于以下问题:PHP DB::connect方法的具体用法?PHP DB::connect怎么用?PHP DB::connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SilverStripe\ORM\DB的用法示例。


在下文中一共展示了DB::connect方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: ErrorControlChain

require_once 'core/startup/ErrorControlChain.php';
require_once 'core/startup/ParameterConfirmationToken.php';
// Prepare tokens and execute chain
$reloadToken = ParameterConfirmationToken::prepare_tokens(array('isTest', 'isDev', 'flush'));
$chain = new ErrorControlChain();
$chain->then(function ($chain) use($reloadToken) {
    // If no redirection is necessary then we can disable error supression
    if (!$reloadToken) {
        $chain->setSuppression(false);
    }
    // Load in core
    require_once 'core/Core.php';
    // Connect to database
    global $databaseConfig;
    if ($databaseConfig) {
        DB::connect($databaseConfig);
    }
    // Check if a token is requesting a redirect
    if (!$reloadToken) {
        return;
    }
    // Otherwise, we start up the session if needed
    if (!isset($_SESSION) && Session::request_contains_session_id()) {
        Session::start();
    }
    // Next, check if we're in dev mode, or the database doesn't have any security data, or we are admin
    if (Director::isDev() || !Security::database_is_ready() || Permission::check('ADMIN')) {
        return $reloadToken->reloadWithToken();
    }
    // Fail and redirect the user to the login page
    $loginPage = Director::absoluteURL(Security::config()->login_url);
开发者ID:jacobbuck,项目名称:silverstripe-framework,代码行数:31,代码来源:main.php

示例2: doBuild

 /**
  * Updates the database schema, creating tables & fields as necessary.
  *
  * @param boolean $quiet Don't show messages
  * @param boolean $populate Populate the database, as well as setting up its schema
  * @param bool $testMode
  */
 public function doBuild($quiet = false, $populate = true, $testMode = false)
 {
     if ($quiet) {
         DB::quiet();
     } else {
         $conn = DB::get_conn();
         // Assumes database class is like "MySQLDatabase" or "MSSQLDatabase" (suffixed with "Database")
         $dbType = substr(get_class($conn), 0, -8);
         $dbVersion = $conn->getVersion();
         $databaseName = method_exists($conn, 'currentDatabase') ? $conn->getSelectedDatabase() : "";
         if (Director::is_cli()) {
             echo sprintf("\n\nBuilding database %s using %s %s\n\n", $databaseName, $dbType, $dbVersion);
         } else {
             echo sprintf("<h2>Building database %s using %s %s</h2>", $databaseName, $dbType, $dbVersion);
         }
     }
     // Set up the initial database
     if (!DB::is_active()) {
         if (!$quiet) {
             echo '<p><b>Creating database</b></p>';
         }
         // Load parameters from existing configuration
         global $databaseConfig;
         if (empty($databaseConfig) && empty($_REQUEST['db'])) {
             user_error("No database configuration available", E_USER_ERROR);
         }
         $parameters = !empty($databaseConfig) ? $databaseConfig : $_REQUEST['db'];
         // Check database name is given
         if (empty($parameters['database'])) {
             user_error("No database name given; please give a value for \$databaseConfig['database']", E_USER_ERROR);
         }
         $database = $parameters['database'];
         // Establish connection and create database in two steps
         unset($parameters['database']);
         DB::connect($parameters);
         DB::create_database($database);
     }
     // Build the database.  Most of the hard work is handled by DataObject
     $dataClasses = ClassInfo::subclassesFor('SilverStripe\\ORM\\DataObject');
     array_shift($dataClasses);
     if (!$quiet) {
         if (Director::is_cli()) {
             echo "\nCREATING DATABASE TABLES\n\n";
         } else {
             echo "\n<p><b>Creating database tables</b></p>\n\n";
         }
     }
     // Initiate schema update
     $dbSchema = DB::get_schema();
     $dbSchema->schemaUpdate(function () use($dataClasses, $testMode, $quiet) {
         foreach ($dataClasses as $dataClass) {
             // Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
             if (!class_exists($dataClass)) {
                 continue;
             }
             // Check if this class should be excluded as per testing conventions
             $SNG = singleton($dataClass);
             if (!$testMode && $SNG instanceof TestOnly) {
                 continue;
             }
             // Log data
             if (!$quiet) {
                 if (Director::is_cli()) {
                     echo " * {$dataClass}\n";
                 } else {
                     echo "<li>{$dataClass}</li>\n";
                 }
             }
             // Instruct the class to apply its schema to the database
             $SNG->requireTable();
         }
     });
     ClassInfo::reset_db_cache();
     if ($populate) {
         if (!$quiet) {
             if (Director::is_cli()) {
                 echo "\nCREATING DATABASE RECORDS\n\n";
             } else {
                 echo "\n<p><b>Creating database records</b></p>\n\n";
             }
         }
         foreach ($dataClasses as $dataClass) {
             // Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
             // Test_ indicates that it's the data class is part of testing system
             if (strpos($dataClass, 'Test_') === false && class_exists($dataClass)) {
                 if (!$quiet) {
                     if (Director::is_cli()) {
                         echo " * {$dataClass}\n";
                     } else {
                         echo "<li>{$dataClass}</li>\n";
                     }
                 }
                 singleton($dataClass)->requireDefaultRecords();
//.........这里部分代码省略.........
开发者ID:jacobbuck,项目名称:silverstripe-framework,代码行数:101,代码来源:DatabaseAdmin.php

示例3: create_temp_db

 public static function create_temp_db()
 {
     // Disable PHPUnit error handling
     restore_error_handler();
     // Create a temporary database, and force the connection to use UTC for time
     global $databaseConfig;
     $databaseConfig['timezone'] = '+0:00';
     DB::connect($databaseConfig);
     $dbConn = DB::get_conn();
     $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
     $dbname = strtolower(sprintf('%stmpdb', $prefix)) . rand(1000000, 9999999);
     while (!$dbname || $dbConn->databaseExists($dbname)) {
         $dbname = strtolower(sprintf('%stmpdb', $prefix)) . rand(1000000, 9999999);
     }
     $dbConn->selectDatabase($dbname, true);
     $st = Injector::inst()->create('SapphireTest');
     $st->resetDBSchema();
     // Reinstate PHPUnit error handling
     set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'));
     return $dbname;
 }
开发者ID:jacobbuck,项目名称:silverstripe-framework,代码行数:21,代码来源:SapphireTest.php

示例4: install


//.........这里部分代码省略.........
        $this->statusMessage("Setting up 'mysite/_config/config.yml'");
        $this->writeToFile("mysite/_config/config.yml", <<<YML
---
Name: mysite
After:
  - 'framework/*'
  - 'cms/*'
---
# YAML configuration for SilverStripe
# See http://doc.silverstripe.org/framework/en/topics/configuration
# Caution: Indentation through two spaces, not tabs
SilverStripe\\View\\SSViewer:
  themes:
    - '{$theme}'
    - '\$default'
SilverStripe\\i18n\\i18n:
  default_locale: '{$locale}'
YML
);
        if (!$this->checkModuleExists('cms')) {
            $this->writeToFile("mysite/code/RootURLController.php", <<<PHP
<?php

use SilverStripe\\Control\\Controller;

class RootURLController extends Controller {

\tpublic function index() {
\t\techo "<html>Your site is now set up. Start adding controllers to mysite to get started.</html>";
\t}

}
PHP
);
        }
        // Write the appropriate web server configuration file for rewriting support
        if ($this->hasRewritingCapability()) {
            if ($isApache) {
                $this->statusMessage("Setting up '.htaccess' file...");
                $this->createHtaccess();
            } elseif ($isIIS) {
                $this->statusMessage("Setting up 'web.config' file...");
                $this->createWebConfig();
            }
        }
        // Load the SilverStripe runtime
        $_SERVER['SCRIPT_FILENAME'] = dirname(realpath($_SERVER['SCRIPT_FILENAME'])) . '/' . FRAMEWORK_NAME . '/main.php';
        chdir(FRAMEWORK_NAME);
        // Rebuild the manifest
        $_GET['flush'] = true;
        // Show errors as if you're in development mode
        $_SESSION['isDev'] = 1;
        $this->statusMessage("Building database schema...");
        require_once 'Core/Core.php';
        // Build database
        $con = new Controller();
        $con->pushCurrent();
        global $databaseConfig;
        DB::connect($databaseConfig);
        $dbAdmin = new DatabaseAdmin();
        $dbAdmin->doInit();
        $dbAdmin->doBuild(true);
        // Create default administrator user and group in database
        // (not using Security::setDefaultAdmin())
        $adminMember = Security::findAnAdministrator();
        $adminMember->Email = $config['admin']['username'];
        $adminMember->Password = $config['admin']['password'];
        $adminMember->PasswordEncryption = Security::config()->encryption_algorithm;
        try {
            $this->statusMessage('Creating default CMS admin account...');
            $adminMember->write();
        } catch (Exception $e) {
            $this->statusMessage(sprintf('Warning: Default CMS admin account could not be created (error: %s)', $e->getMessage()));
        }
        $_SESSION['username'] = $config['admin']['username'];
        $_SESSION['password'] = $config['admin']['password'];
        if (!$this->errors) {
            if (isset($_SERVER['HTTP_HOST']) && $this->hasRewritingCapability()) {
                $this->statusMessage("Checking that friendly URLs work...");
                $this->checkRewrite();
            } else {
                require_once 'Core/Startup/ParameterConfirmationToken.php';
                $token = new ParameterConfirmationToken('flush');
                $params = http_build_query($token->params());
                $destinationURL = 'index.php/' . ($this->checkModuleExists('cms') ? "home/successfullyinstalled?{$params}" : "?{$params}");
                echo <<<HTML
\t\t\t\t<li>SilverStripe successfully installed; I am now redirecting you to your SilverStripe site...</li>
\t\t\t\t<script>
\t\t\t\t\tsetTimeout(function() {
\t\t\t\t\t\twindow.location = "{$destinationURL}";
\t\t\t\t\t}, 2000);
\t\t\t\t</script>
\t\t\t\t<noscript>
\t\t\t\t<li><a href="{$destinationURL}">Click here to access your site.</a></li>
\t\t\t\t</noscript>
HTML;
            }
        }
        return $this->errors;
    }
开发者ID:SpiritLevel,项目名称:silverstripe-framework,代码行数:101,代码来源:install.php5


注:本文中的SilverStripe\ORM\DB::connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。