草庐IT

php - Doctrine Proxy 不初始化

coder 2023-10-10 原文

当我将文件上传到 Symfony 时,它是按应有的方式上传的。我使用了有关文件上传的 Symfony 教程并对其进行了修改以满足我的需要。

if($form->isValid())
{
    $em = $this->oStarter->getEntityManager();

    // Save file to database
    $uploadedFile = new ProfilePicture();
    $uploadedFile->setFile($formData["profile_picture"]);
    $user->setProfilePicture($uploadedFile);
    $uploadedFile->setUser($user);

    $em->persist($uploadedFile);
    $em->persist($user);

    $em->flush();

    // Other things like Twig templates etc..

此代码用于上传图片并将其设置为用户的个人资料图片。通过Controller中的$this->getUser()找到用户。当我在刷新后输出实体时,它向我显示了一个有效实体的转储,正如我所期望的那样。

当我访问该用户的个人资料页面时,找不到图像。当我检查 MySQL 表时,我找到了具有正确 ID 和路径的 ProfilePicture 的有效条目。如您所料,用户还具有对 ProfilePicture 的 ID 的引用。相反,该页面向我显示了以下转储:

$avatar = $user->getProfilePicture();
$path = $avatar->getWebPath();
Debug::dump($avatar);


object(stdClass)#938 (8) 
{
  ["__CLASS__"]=>
  string(42) "Takeabyte\CoreBundle\Entity\ProfilePicture"
  ["__IS_PROXY__"]=>
  bool(true)
  ["__PROXY_INITIALIZED__"]=>
  bool(false)
  ["id"]=>
  NULL
  ["user"]=>
  object(stdClass)#1011 (52) {
    ["__CLASS__"]=>
    string(32) "Takeabyte\CoreBundle\Entity\User"
    ["id"]=>
    int(11)
    // lots of user info
    }
  ["file"]=>
  NULL
  ["path"]=>
  NULL
  ["temp"]=>
  NULL
}

转储显示没有设置路径。即使在调用了 Proxy 的函数之后,真正的数据似乎也没有被加载。我做错了什么?

编辑 实体如下:

/**
 * @author Tim Cocu
 * @author Rick Slinkman
 *
 * @ORM\Entity
 * @ORM\Table(name="profilepictures")
 * @Database(target="client")
 */
class ProfilePicture extends Image
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="\Takeabyte\CoreBundle\Entity\User", mappedBy="profilePicture")
     */
    private $user;

    // accessors and mutators
}

/**
 * Description of Image
 *
 * @ORM\MappedSuperclass
 * @Database(target="client")
 * @author Rick Slinkman (r.slinkman@take-a-byte.eu)
 */
class Image extends MediaFile
{
    /**
     * @param ClassMetadata $metadata
     */
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('file', new Assert\File(array(
            'maxSize' => 6000000,
            'mimeTypes' => array(
                "image/jpeg",
                "image/png",
                "image/gif"
            ),
        )));
    }

    // other functions
}

/**
 * Standard container of an uploaded media file
 * @author Rick Slinkman
 * @author Tim Cocu
 * 
 * @ORM\HasLifecycleCallbacks
 * @ORM\MappedSuperclass
 * @Database(target="client")
 * 
 * Based on:
 * http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
 */
class MediaFile 
{
    /**
     * @Assert\File(maxSize="6000000")
     */
    protected $file;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $path;

    /**
     * Temporary storage on file moving.
     */
    protected $temp;

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) 
        {
            // do whatever you want to generate a unique name
            $filename = sha1(uniqid(mt_rand(), true));
            $this->path = $filename.'.'.$this->getFile()->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->getFile()) 
        {
            return;
        }

        // if there is an error when moving the file, an exception will
        // be automatically thrown by move(). This will properly prevent
        // the entity from being persisted to the database on error
        $this->getFile()->move($this->getUploadRootDir(), $this->path);

        // check if we have an old image
        if (isset($this->temp)) 
        {
            // delete the old image
            unlink($this->getUploadRootDir().'/'.$this->temp);
            // clear the temp image path
            $this->temp = null;
        }
        $this->file = null;
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if ($file = $this->getAbsolutePath()) 
        {
            unlink($file);
        }
    }

    // other functions 
}

/**
 * @author: Jordy - j.deruijter@take-a-byte.eu
 * @author: Rick - r.slinkman@take-a-byte.eu
 * @author: Tim - t.cocu@take-a-byte.eu
 * @since: 25-10-13
 *
 * @ORM\Entity
 * @ORM\Table(name="fos_user_user")
 * @Database(target="client")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    // Lots of data

    /**
     * @var ProfilePicture
     * @ORM\OneToOne(targetEntity="\Takeabyte\CoreBundle\Entity\ProfilePicture", inversedBy="user")
     */
    protected $profilePicture;

    // Even more data
}

最佳答案

我想大约一年前我遇到过类似的错误。

您会看到,当您进行身份验证时,您的 User 实体的序列化(文本)版本存储在您的 session 中。当您访问防火墙后面的页面时,它会被反序列化并再次转换为 User。但是,由于您与 ProfilePicture 相关,并不急切,并且在序列化期间此属性未序列化。代理对象不可序列化...

因此,当它试图从 session 中检索经过身份验证的用户时,其 $profilePicture 属性被设置为 NULL

这会是你的情况吗?

想法#1:

  1. 在您的 User 实体中将关系设置为 EAGER
  2. 尝试设置 always_authenticate_before_granting: true 在你的 confir.yml (安全 block )

我相信这会导致安全性进入数据库并在每次访问页面时重新获取 User 实体...

想法#2:

刷新您的用户实体并手动获取profilePicture。也许您也可以在 session 中单独存储用户个人资料图片?

关于php - Doctrine Proxy 不初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20657839/

有关php - Doctrine Proxy 不初始化的更多相关文章

  1. ruby-on-rails - 未初始化的常量 Psych::Syck (NameError) - 2

    在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到ruby​​gems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决

  2. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  3. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  4. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  5. ruby - 为什么当我调用类的实例方法时,初始化不显示为方法? - 2

    我正在写一篇关于在Ruby中几乎一切都是对象的博客文章,我试图通过以下示例来展示这一点:classCoolBeansattr_accessor:beansdefinitialize@bean=[]enddefcount_beans@beans.countendend所以从类中我们可以看出它有4个方法(当然,除非我错了):它可以在创建新实例时初始化一个默认的空bean数组它可以计算它有多少个bean它可以读取它有多少个bean(通过attr_accessor)它可以向空数组写入(或添加)更多bean(也通过attr_accessor)但是,当我询问类本身它有哪些实例方法时,我没有看到默认

  6. ruby-on-rails - 为什么在 Rails 5.1.1 中删除了 session 存储初始化程序 - 2

    我去了这个website查看Rails5.0.0和Rails5.1.1之间的区别为什么5.1.1不再包含:config/initializers/session_store.rb?谢谢 最佳答案 这是删除它的提交:Setupdefaultsessionstoreinternally,nolongerthroughanapplicationinitializer总而言之,新应用没有该初始化器,session存储默认设置为cookie存储。即与在该初始值设定项的生成版本中指定的值相同。 关于

  7. ruby-on-rails - NameError(未初始化常量 Unzipper::Zip)但仅在 Heroku 部署(Rails)上 - 2

    我有一个类unzipper.rb,它使用Rubyzip解压文件。在我的本地环境中,我可以成功解压缩文件,而无需使用require'zip'明确包含依赖项但是在Heroku上,我得到一个NameError(uninitializedconstantUnzipper::Zip)我只能通过使用明确的require来解决问题:为什么这在H​​eroku环境中是必需的,但在本地主机上却不是?我的印象是Rails自动需要所有gem。app/services/unzipper.rbrequire'zip'#OnlyrequiredforHeroku.Workslocallywithout!class

  8. ruby - 安装 gem 时未初始化的常量 Psych::Syck - 2

    我将gem推送到ruby​​gems.org,当我执行“geminstall(gem)”时出现此错误:ERROR:Whileexecutinggem...(NameError)uninitializedconstantPsych::Syck我可以执行“gembuild(gem).gemspec”来生成本地gem,然后geminstall(gem).gem并且安装正常。我还可以将gem放入我的Rails应用程序的Gemfile中,并带有指向Github存储库的指针,这也可以。我试过在多台计算机上安装gem(来自ruby​​gems.org,它们都遇到相同的错误。我不知道是什么原因导致从r

  9. ruby - 有没有一种 Ruby 方法可以删除初始化程序中的样板代码? - 2

    我写了很多initialize代码,将attrs设置为参数,类似于:classSiteClientattr_reader:login,:password,:domaindefinitialize(login,password,domain='somedefaultsite.com')@login=login@password=password@domain=domainendend有没有更像Ruby的方式来做到这一点?我觉得我在一遍又一遍地编写相同的样板设置代码。 最佳答案 您可以使用rubyStruct:classMyClass或

  10. ruby-on-rails - Spring 不起作用。 [未初始化常量 Spring::SID::DL] - 2

    我无法运行Spring。这是错误日志。myid-no-MacBook-Pro:myid$spring/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/lib/spring/sid.rb:17:in`fiddle_func':uninitializedconstantSpring::SID::DL(NameError)from/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/li

随机推荐