草庐IT

php - SOLID - 单一职责原则是否适用于类中的方法?

coder 2024-01-02 原文

我不确定我的类中的这个方法是否违反了单一职责原则,

public function save(Note $note)
{
    if (!_id($note->getid())) {

        $note->setid(idGenerate('note'));

        $q = $this->db->insert($this->table)
                      ->field('id', $note->getid(), 'id');

    } else {
        $q = $this->db->update($this->table)
                      ->where('AND', 'id', '=', $note->getid(), 'id');
    }

    $q->field('title', $note->getTitle())
      ->field('content', $note->getContent());

    $this->db->execute($q);

    return $note;
}

基本上它在一个方法中做两项工作 - 插入或更新。

我是否应该将其分离为两个方法而不是遵守单一职责原则?

但 SRP 仅适用于类(class),不是吗?它适用于类中的方法吗?

建议零售价 -

a class should have only a single responsibility (i.e. only one potential change in the software's specification should be able to affect the specification of the class)

编辑:

另一种用于列出笔记(包括许多不同类型的列表)、搜索笔记等的方法...

public function getBy(array $params = array())
{
    $q = $this->db->select($this->table . ' n')
                  ->field('title')
                  ->field('content')
                  ->field('creator', 'creator', 'id')
                  ->field('created_on')
                  ->field('updated_on');

    if (isset($params['id'])) {
        if (!is_array($params['id'])) {
            $params['id'] = array($params['id']);
        }

        $q->where('AND', 'id', 'IN', $params['id'], 'id');
    }

    if (isset($params['user_id'])) {
        if (!is_array($params['user_id'])) {
            $params['user_id'] = array($params['user_id']);
        }

        # Handling of type of list: created / received
        if (isset($params['type']) && $params['type'] == 'received') {
            $q
                ->join(
                    'inner',
                    $this->table_share_link . ' s',
                    's.target_id = n.id AND s.target_type = \'note\''
                )
                ->join(
                    'inner',
                    $this->table_share_link_permission . ' p',
                    'p.share_id = s.share_id'
                )
                # Is it useful to know the permission assigned?
                ->field('p.permission')
                # We don't want get back own created note
                ->where('AND', 'n.creator', 'NOT IN', $params['user_id'], 'uuid');
            ;

            $identity_id = $params['user_id'];

            # Handling of group sharing
            if (isset($params['user_group_id']) /*&& count($params['user_group_id'])*/) {
                if (!is_array($params['user_group_id'])) {
                    $params['user_group_id'] = array($params['user_group_uuid']);
                }

                $identity_id = array_merge($identity_id, $params['user_group_id']);
            }

             $q->where('AND', 'p.identity_id', 'IN', $identity_id, 'id');

        } else {
            $q->where('AND', 'n.creator', 'IN', $params['user_id'], 'id');
        }
    }

    # If string search by title
    if (isset($params['find']) && $params['find']) {
        $q->where('AND', 'n.title', 'LIKE', '%' . $params['find'] . '%');
    }

    # Handling of sorting
    if (isset($params['order'])) {
        if ($params['order'] == 'title') {
            $orderStr = 'n.title';

        } else {
            $orderStr = 'n.updated_on';
        }

        if ($params['order'] == 'title') {
            $orderStr = 'n.title';

        } else {
            $orderStr = 'n.updated_on';
        }

        $q->orderBy($orderStr);

    } else {
        // Default sorting
        $q->orderBy('n.updated_on DESC');
    }

    if (isset($params['limit'])) {
        $q->limit($params['limit'], isset($params['offset']) ? $params['offset'] : 0);
    }

    $res = $this->db->execute($q);

    $notes = array();

    while ($row = $res->fetchRow()) {
        $notes[$row->uuid] = $this->fromRow($row);
    }

    return $notes;
}

最佳答案

该方法将注释保存到数据库。如果那是它应该做的,那么这是一个单一的责任并且实现很好。您需要将决定是插入还是更新的逻辑放在某处,这似乎是一个不错的地方。

只有当您需要在没有隐式决策逻辑的情况下显式执行插入或更新时,才值得将这两者分离到可以单独调用的不同方法中。但目前,将它们保持在相同的方法中可以简化代码(因为后半部分是共享的),所以这可能是最好的实现方式。

示例:

public function save(Note $note) {
    if (..) {
        $this->insert($note);
    } else {
        $this->update($note);
    }
}

public function insert(Note $note) {
    ..
}

public function update(Note $note) {
    ..
}

如果您有时出于某种原因需要显式调用 insertupdate ,那么上面的内容就有意义了。不过,SRP 并不是这种分离的真正原因。

关于php - SOLID - 单一职责原则是否适用于类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30861882/

有关php - SOLID - 单一职责原则是否适用于类中的方法?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  6. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  9. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  10. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

随机推荐