Fatal error: Class 'MongoDate' not found w

2019-06-24 08:20发布

I am trying to configure MongoDB to work with my Laravel 5.1 Homestead instance on a virtual Ubuntu 14.04 machine. I was able to successfully install the latest version of MongoDB which supports PHP 7.0 using sudo pecl install mongodb (this is correct for 7.0, not sudo pecl install mongo anymore).

I then added the extension in my php.ini files (all three) on my Ubuntu machine, each in:

  • /etc/php/7.0/cli/php.ini
  • /etc/php/7.0/fpm/php.ini
  • /etc/php/7.0/cgi/php.ini

This is the extension I wrote which is correct for use with PHP 7.0:

  • extension=mongodb.so (not mongo.so anymore)

When I run phpinfo() in my browser, it states that MongoDB is properly configured with my PHP 7.0.

If MongoDB is properly configured, how come I keep getting:

Fatal error: Class 'MongoDate' not found

when I try to run my migrations and seeds with php artisan migrate:refresh --seed?

I already tried:

  • rebooting the Ubuntu machine with vagrant reload and vagrant reload --provision
  • Restarting PHP and Nginx with sudo service nginx restart and sudo service php7.0-fpm restart

Neither have worked.

2条回答
爷的心禁止访问
2楼-- · 2019-06-24 08:32

Throughout our app we were regularly converting unix timestamps into MongoDate instances. Example:

new MongoDate(strtotime('-1 day'));

I've therefore created a class to allow conversion between unix timestamps and the new MongoDB\BSON\UTCDateTime, and back

<?php

class MongoHelper {

    const SECONDS_IN_A_MILLISECOND = 1000;

    public static function getMongoUTCDateTimeFromUnixTimestamp($timestamp) {
        return new \MongoDB\BSON\UTCDateTime(intval($timestamp * self::SECONDS_IN_A_MILLISECOND));
    }

    public static function getUnixTimestampFromMongoUTCDateTime(\MongoDB\BSON\UTCDateTime $utc_date_time) {
        return intval((string) $utc_date_time / self::SECONDS_IN_A_MILLISECOND);
    }
}

Example usage:

MongoHelper::getMongoUTCDateTimeFromUnixTimestamp(strtotime('-1 day'));
查看更多
姐就是有狂的资本
3楼-- · 2019-06-24 08:37

As you mentioned you're using the new Mongo extension for PHP 7.

The class names have changed from the older version, i.e.

MongoClient is now MongoDB\Driver\Manager

MongoDate is now MongoDB\BSON\UTCDateTime

I'm not sure how backwards compatible everything is, but this should get you started!

查看更多
登录 后发表回答